[
  {
    "path": ".gitignore",
    "content": "*.iml\n.gradle\n/local.properties\n/.idea/workspace.xml\n/.idea/libraries\n.DS_Store\n/build\n/captures\n.idea\n\n# Built application files\n*.apk\n*.ap_\n\n# Files for the ART/Dalvik VM\n*.dex\n\n# Java class files\n*.class\n\n# Generated files\nbin/\ngen/\nout/\n\n# Gradle files\n.gradle/\nbuild/\n\n# Local configuration file (sdk path, etc)\nlocal.properties\n\n# Proguard folder generated by Eclipse\nproguard/\n\n# Log Files\n*.log\n\n# Android Studio Navigation editor temp files\n.navigation/\n\n# Android Studio captures folder\ncaptures/\n\n# Intellij\n*.iml\n.idea/workspace.xml\n\n# Keystore files\n*.jks\n"
  },
  {
    "path": "README.md",
    "content": "# android_silk_v3_decoder\nConvert silk v3 audio files (QQ &amp; WeChat voice files) to mp3 files on android.\n\nplease refer to this app, https://play.google.com/store/apps/details?id=com.pleasure.trace_wechat\n\n#2019-04-26 更新构建系统为Cmake+Clang(NDK15(记不清是不是)以后官方默认),转换成kotlin编写,修改lame/machine.h报错的部分,修改silkx JNI入口参数错误问题,增加权限验证(Android7+),替换Android支持包为AndroidX\n\n\n国内的可以搜索“微痕迹”，此应用集成了微信和ＱＱ语音的转成mp3的功能，另外提供管理微信ＱＱ图片语音文件的功能。\n因为语音转换这部分参考了一些开源工程，特将此部分开源，回馈开源社区。\n"
  },
  {
    "path": "app/.gitignore",
    "content": "/build\n*.iml\n.gradle\n.idea\n.DS_Store\n/captures\n.externalNativeBuild"
  },
  {
    "path": "app/CMakeLists.txt",
    "content": "# documentation: https://d.android.com/studio/projects/add-native-code.html\ncmake_minimum_required(VERSION 3.4.1)\nSET(CMAKE_BUILE_TYPE DEBUG)\n\nif (${ANDROID_ABI} STREQUAL arm)\n    set(CMAKE_C_FLAGS \"${CMAKE_C_FLAGS} -mfpu=vfp -mfloat-abi=softfp -fno-short-enums\")\nendif ()\nset(CMAKE_CPP_FLAGS \"${CMAKE_CPP_FLAGS}  -std=c++11\")\nSET(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} -Wl,-s\")\n\n#find_library(log-lib log)\n#find_library(z-lib z)\n#include_directories(jni/include)\n#message(\"搜索结果:\")\nadd_library(mp3lame STATIC jni/libmp3lame/bitstream.c\n        jni/libmp3lame/fft.c\n        jni/libmp3lame/id3tag.c\n        jni/libmp3lame/mpglib_interface.c\n        jni/libmp3lame/presets.c\n        jni/libmp3lame/quantize.c\n        jni/libmp3lame/reservoir.c\n        jni/libmp3lame/tables.c\n        jni/libmp3lame/util.c\n        jni/libmp3lame/VbrTag.c\n        jni/libmp3lame/encoder.c\n        jni/libmp3lame/gain_analysis.c\n        jni/libmp3lame/lame.c\n        jni/libmp3lame/newmdct.c\n        jni/libmp3lame/psymodel.c\n        jni/libmp3lame/quantize_pvt.c\n        jni/libmp3lame/set_get.c\n        jni/libmp3lame/takehiro.c\n        jni/libmp3lame/vbrquantize.c\n        jni/libmp3lame/version.c\n        )\n\ntarget_include_directories(mp3lame PUBLIC jni/include/lame.h)\n\nadd_library(silkx SHARED\n\n        jni/SKP_Silk_dec_API.c\n        jni/SKP_Silk_create_init_destroy.c\n        jni/SKP_Silk_decoder_set_fs.c\n        jni/SKP_Silk_tables_NLSF_CB0_10.c\n        jni/SKP_Silk_tables_NLSF_CB1_10.c\n        jni/SKP_Silk_tables_NLSF_CB0_16.c\n        jni/SKP_Silk_tables_NLSF_CB1_16.c\n        jni/SKP_Silk_tables_other.c\n        jni/SKP_Silk_CNG.c\n        jni/SKP_Silk_NLSF2A_stable.c\n        jni/SKP_Silk_NLSF2A.c\n        jni/SKP_Silk_bwexpander_32.c\n        jni/SKP_Silk_LSF_cos_table.c\n        jni/SKP_Silk_bwexpander.c\n        jni/SKP_Silk_LPC_inv_pred_gain.c\n        jni/SKP_Silk_LPC_synthesis_filter.c\n        jni/SKP_Silk_LPC_synthesis_order16.c\n        jni/SKP_Silk_PLC.c\n        jni/SKP_Silk_sum_sqr_shift.c\n        jni/SKP_Silk_decode_frame.c\n        jni/SKP_Silk_range_coder.c\n        jni/SKP_Silk_decode_parameters.c\n        jni/SKP_Silk_tables_pitch_lag.c\n        jni/SKP_Silk_tables_type_offset.c\n        jni/SKP_Silk_gain_quant.c\n        jni/SKP_Silk_lin2log.c\n        jni/SKP_Silk_NLSF_MSVQ_decode.c\n        jni/SKP_Silk_NLSF_stabilize.c\n        jni/SKP_Silk_sort.c\n        jni/SKP_Silk_decode_pitch.c\n        jni/SKP_Silk_pitch_est_tables.c\n        jni/SKP_Silk_tables_LTP.c\n        jni/SKP_Silk_tables_gain.c\n        jni/SKP_Silk_decode_pulses.c\n        jni/SKP_Silk_tables_pulses_per_block.c\n        jni/SKP_Silk_code_signs.c\n        jni/SKP_Silk_tables_sign.c\n        jni/SKP_Silk_shell_coder.c\n        jni/SKP_Silk_biquad.c\n        jni/SKP_Silk_decode_core.c\n        jni/SKP_Silk_MA.c\n        jni/SKP_Silk_resampler.c\n        jni/SKP_Silk_resampler_private_down4.c\n        jni/SKP_Silk_resampler_rom.c\n        jni/SKP_Silk_resampler_private_copy.c\n        jni/SKP_Silk_resampler_private_down_FIR.c\n        jni/SKP_Silk_resampler_private_AR2.c\n        jni/SKP_Silk_resampler_down2.c\n        jni/SKP_Silk_resampler_private_up2_HQ.c\n        jni/SKP_Silk_resampler_private_IIR_FIR.c\n        jni/SKP_Silk_resampler_private_ARMA4.c\n        jni/SKP_Silk_resampler_private_up4.c\n        jni/SKP_Silk_resampler_up2.c\n        jni/SKP_Silk_log2lin.c\n        jni/silk.c\n        jni/decoder.cpp\n#        jni/decoder.c\n        )\n#target_include_directories(silkx PUBLIC\n#        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/jni/include>\n#        $<INSTALL_INTERFACE:jni/include>  # <prefix>/include/mylib\n#        )\ntarget_include_directories(mp3lame PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/jni/include)\n\n\ntarget_link_libraries(silkx\n        mp3lame\n        log\n        z )\n\n"
  },
  {
    "path": "app/build.gradle",
    "content": "apply plugin: 'com.android.application'\napply plugin: 'kotlin-android-extensions'\napply plugin: 'kotlin-android'\n\nandroid {\n    compileSdkVersion 28\n\n    defaultConfig {\n        applicationId \"com.ketian.android.silkv3\"\n        minSdkVersion 16\n        targetSdkVersion 28\n        versionCode 1\n        versionName \"1.0\"\n\n        externalNativeBuild {\n            cmake {\n                cFlags \"-frtti -fexceptions -Werror -DANDROID -DSTDC_HEADERS  -Werror  -fno-short-enums\"\n                cppFlags \"-frtti -fexceptions -Werror -DANDROID -DSTDC_HEADERS  -Werror  -std=gnu++0x\"\n            }\n            ndk {    //  abiFilters \"armeabi\"\n                abiFilters \"armeabi-v7a\", \"x86_64\",\"x86\",\"arm64-v8a\"\n            }\n        }\n    }\n\n    externalNativeBuild {\n        cmake {\n            path \"CMakeLists.txt\"\n        }\n    }\n\n    buildTypes {\n        release {\n            minifyEnabled false\n            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n        }\n    }\n}\n\ndependencies {\n    implementation fileTree(include: ['*.jar'], dir: 'libs')\n    implementation 'androidx.appcompat:appcompat:1.0.2'\n    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'\n    implementation 'androidx.recyclerview:recyclerview:1.0.0'\n    implementation \"androidx.core:core-ktx:1.0.1\"\n    implementation \"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version\"\n}\nrepositories {\n    mavenCentral()\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_A2NLSF.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/* Conversion between prediction filter coefficients and NLSFs  */\n/* Requires the order to be an even number                      */\n/* A piecewise linear approximation maps LSF <-> cos(LSF)       */\n/* Therefore the result is not accurate NLSFs, but the two      */\n/* function are accurate inverses of each other                 */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Number of binary divisions */\n#define BIN_DIV_STEPS_A2NLSF_FIX      3 /* must be no higher than 16 - log2( LSF_COS_TAB_SZ_FIX ) */\n#define QPoly                        16\n#define MAX_ITERATIONS_A2NLSF_FIX    30\n\n/* Flag for using 2x as many cosine sampling points, reduces the risk of missing a root */\n#define OVERSAMPLE_COSINE_TABLE       0\n\n/* Helper function for A2NLSF(..)                    */\n/* Transforms polynomials from cos(n*f) to cos(f)^n  */\nSKP_INLINE void SKP_Silk_A2NLSF_trans_poly(\n    SKP_int32        *p,    /* I/O    Polynomial                                */\n    const SKP_int    dd     /* I      Polynomial order (= filter order / 2 )    */\n)\n{\n    SKP_int k, n;\n    \n    for( k = 2; k <= dd; k++ ) {\n        for( n = dd; n > k; n-- ) {\n            p[ n - 2 ] -= p[ n ];\n        }\n        p[ k - 2 ] -= SKP_LSHIFT( p[ k ], 1 );\n    }\n}    \n#if EMBEDDED_ARM<6\n/* Helper function for A2NLSF(..)                    */\n/* Polynomial evaluation                             */\nSKP_INLINE SKP_int32 SKP_Silk_A2NLSF_eval_poly(    /* return the polynomial evaluation, in QPoly */\n    SKP_int32        *p,    /* I    Polynomial, QPoly        */\n    const SKP_int32   x,    /* I    Evaluation point, Q12    */\n    const SKP_int    dd     /* I    Order                    */\n)\n{\n    SKP_int   n;\n    SKP_int32 x_Q16, y32;\n\n    y32 = p[ dd ];                                    /* QPoly */\n    x_Q16 = SKP_LSHIFT( x, 4 );\n    for( n = dd - 1; n >= 0; n-- ) {\n        y32 = SKP_SMLAWW( p[ n ], y32, x_Q16 );       /* QPoly */\n    }\n    return y32;\n}\n#else\nSKP_int32 SKP_Silk_A2NLSF_eval_poly(    /* return the polynomial evaluation, in QPoly */\n    SKP_int32        *p,    /* I    Polynomial, QPoly        */\n    const SKP_int32   x,    /* I    Evaluation point, Q12    */\n    const SKP_int    dd     /* I    Order                    */\n);\n#endif\n\nSKP_INLINE void SKP_Silk_A2NLSF_init(\n     const SKP_int32    *a_Q16,\n     SKP_int32          *P, \n     SKP_int32          *Q, \n     const SKP_int      dd\n) \n{\n    SKP_int k;\n\n    /* Convert filter coefs to even and odd polynomials */\n    P[dd] = SKP_LSHIFT( 1, QPoly );\n    Q[dd] = SKP_LSHIFT( 1, QPoly );\n    for( k = 0; k < dd; k++ ) {\n#if( QPoly < 16 )\n        P[ k ] = SKP_RSHIFT_ROUND( -a_Q16[ dd - k - 1 ] - a_Q16[ dd + k ], 16 - QPoly ); /* QPoly */\n        Q[ k ] = SKP_RSHIFT_ROUND( -a_Q16[ dd - k - 1 ] + a_Q16[ dd + k ], 16 - QPoly ); /* QPoly */\n#elif( QPoly == 16 )\n        P[ k ] = -a_Q16[ dd - k - 1 ] - a_Q16[ dd + k ]; // QPoly\n        Q[ k ] = -a_Q16[ dd - k - 1 ] + a_Q16[ dd + k ]; // QPoly\n#else\n        P[ k ] = SKP_LSHIFT( -a_Q16[ dd - k - 1 ] - a_Q16[ dd + k ], QPoly - 16 ); /* QPoly */\n        Q[ k ] = SKP_LSHIFT( -a_Q16[ dd - k - 1 ] + a_Q16[ dd + k ], QPoly - 16 ); /* QPoly */\n#endif\n    }\n\n    /* Divide out zeros as we have that for even filter orders, */\n    /* z =  1 is always a root in Q, and                        */\n    /* z = -1 is always a root in P                             */\n    for( k = dd; k > 0; k-- ) {\n        P[ k - 1 ] -= P[ k ]; \n        Q[ k - 1 ] += Q[ k ]; \n    }\n\n    /* Transform polynomials from cos(n*f) to cos(f)^n */\n    SKP_Silk_A2NLSF_trans_poly( P, dd );\n    SKP_Silk_A2NLSF_trans_poly( Q, dd );\n}\n\n/* Compute Normalized Line Spectral Frequencies (NLSFs) from whitening filter coefficients        */\n/* If not all roots are found, the a_Q16 coefficients are bandwidth expanded until convergence.    */\nvoid SKP_Silk_A2NLSF(\n    SKP_int          *NLSF,                 /* O    Normalized Line Spectral Frequencies, Q15 (0 - (2^15-1)), [d]    */\n    SKP_int32        *a_Q16,                /* I/O  Monic whitening filter coefficients in Q16 [d]                   */\n    const SKP_int    d                      /* I    Filter order (must be even)                                      */\n)\n{\n    SKP_int      i, k, m, dd, root_ix, ffrac;\n    SKP_int32 xlo, xhi, xmid;\n    SKP_int32 ylo, yhi, ymid;\n    SKP_int32 nom, den;\n    SKP_int32 P[ SKP_Silk_MAX_ORDER_LPC / 2 + 1 ];\n    SKP_int32 Q[ SKP_Silk_MAX_ORDER_LPC / 2 + 1 ];\n    SKP_int32 *PQ[ 2 ];\n    SKP_int32 *p;\n\n    /* Store pointers to array */\n    PQ[ 0 ] = P;\n    PQ[ 1 ] = Q;\n\n    dd = SKP_RSHIFT( d, 1 );\n\n    SKP_Silk_A2NLSF_init( a_Q16, P, Q, dd );\n\n    /* Find roots, alternating between P and Q */\n    p = P;    /* Pointer to polynomial */\n    \n    xlo = SKP_Silk_LSFCosTab_FIX_Q12[ 0 ]; // Q12\n    ylo = SKP_Silk_A2NLSF_eval_poly( p, xlo, dd );\n\n    if( ylo < 0 ) {\n        /* Set the first NLSF to zero and move on to the next */\n        NLSF[ 0 ] = 0;\n        p = Q;                      /* Pointer to polynomial */\n        ylo = SKP_Silk_A2NLSF_eval_poly( p, xlo, dd );\n        root_ix = 1;                /* Index of current root */\n    } else {\n        root_ix = 0;                /* Index of current root */\n    }\n    k = 1;                          /* Loop counter */\n    i = 0;                          /* Counter for bandwidth expansions applied */\n    while( 1 ) {\n        /* Evaluate polynomial */\n#if OVERSAMPLE_COSINE_TABLE\n        xhi = SKP_Silk_LSFCosTab_FIX_Q12[   k       >> 1 ] +\n          ( ( SKP_Silk_LSFCosTab_FIX_Q12[ ( k + 1 ) >> 1 ] - \n              SKP_Silk_LSFCosTab_FIX_Q12[   k       >> 1 ] ) >> 1 );    /* Q12 */\n#else\n        xhi = SKP_Silk_LSFCosTab_FIX_Q12[ k ]; /* Q12 */\n#endif\n        yhi = SKP_Silk_A2NLSF_eval_poly( p, xhi, dd );\n        \n        /* Detect zero crossing */\n        if( ( ylo <= 0 && yhi >= 0 ) || ( ylo >= 0 && yhi <= 0 ) ) {\n            /* Binary division */\n#if OVERSAMPLE_COSINE_TABLE\n            ffrac = -128;\n#else\n            ffrac = -256;\n#endif\n            for( m = 0; m < BIN_DIV_STEPS_A2NLSF_FIX; m++ ) {\n                /* Evaluate polynomial */\n                xmid = SKP_RSHIFT_ROUND( xlo + xhi, 1 );\n                ymid = SKP_Silk_A2NLSF_eval_poly( p, xmid, dd );\n\n                /* Detect zero crossing */\n                if( ( ylo <= 0 && ymid >= 0 ) || ( ylo >= 0 && ymid <= 0 ) ) {\n                    /* Reduce frequency */\n                    xhi = xmid;\n                    yhi = ymid;\n                } else {\n                    /* Increase frequency */\n                    xlo = xmid;\n                    ylo = ymid;\n#if OVERSAMPLE_COSINE_TABLE\n                    ffrac = SKP_ADD_RSHIFT( ffrac,  64, m );\n#else\n                    ffrac = SKP_ADD_RSHIFT( ffrac, 128, m );\n#endif\n                }\n            }\n            \n            /* Interpolate */\n            if( SKP_abs( ylo ) < 65536 ) {\n                /* Avoid dividing by zero */\n                den = ylo - yhi;\n                nom = SKP_LSHIFT( ylo, 8 - BIN_DIV_STEPS_A2NLSF_FIX ) + SKP_RSHIFT( den, 1 );\n                if( den != 0 ) {\n                    ffrac += SKP_DIV32( nom, den );\n                }\n            } else {\n                /* No risk of dividing by zero because abs(ylo - yhi) >= abs(ylo) >= 65536 */\n                ffrac += SKP_DIV32( ylo, SKP_RSHIFT( ylo - yhi, 8 - BIN_DIV_STEPS_A2NLSF_FIX ) );\n            }\n#if OVERSAMPLE_COSINE_TABLE\n            NLSF[ root_ix ] = (SKP_int)SKP_min_32( SKP_LSHIFT( (SKP_int32)k, 7 ) + ffrac, SKP_int16_MAX ); \n#else\n            NLSF[ root_ix ] = (SKP_int)SKP_min_32( SKP_LSHIFT( (SKP_int32)k, 8 ) + ffrac, SKP_int16_MAX ); \n#endif\n\n            SKP_assert( NLSF[ root_ix ] >=     0 );\n            SKP_assert( NLSF[ root_ix ] <= 32767 );\n\n            root_ix++;        /* Next root */\n            if( root_ix >= d ) {\n                /* Found all roots */\n                break;\n            }\n            /* Alternate pointer to polynomial */\n            p = PQ[ root_ix & 1 ];\n            \n            /* Evaluate polynomial */\n#if OVERSAMPLE_COSINE_TABLE\n            xlo = SKP_Silk_LSFCosTab_FIX_Q12[ ( k - 1 ) >> 1 ] +\n              ( ( SKP_Silk_LSFCosTab_FIX_Q12[   k       >> 1 ] - \n                  SKP_Silk_LSFCosTab_FIX_Q12[ ( k - 1 ) >> 1 ] ) >> 1 ); // Q12\n#else\n            xlo = SKP_Silk_LSFCosTab_FIX_Q12[ k - 1 ]; // Q12\n#endif\n            ylo = SKP_LSHIFT( 1 - ( root_ix & 2 ), 12 );\n        } else {\n            /* Increment loop counter */\n            k++;\n            xlo    = xhi;\n            ylo    = yhi;\n            \n#if OVERSAMPLE_COSINE_TABLE\n            if( k > 2 * LSF_COS_TAB_SZ_FIX ) {\n#else\n            if( k > LSF_COS_TAB_SZ_FIX ) {\n#endif\n                i++;\n                if( i > MAX_ITERATIONS_A2NLSF_FIX ) {\n                    /* Set NLSFs to white spectrum and exit */\n                    NLSF[ 0 ] = SKP_DIV32_16( 1 << 15, d + 1 );\n                    for( k = 1; k < d; k++ ) {\n                        NLSF[ k ] = SKP_SMULBB( k + 1, NLSF[ 0 ] );\n                    }\n                    return;\n                }\n\n                /* Error: Apply progressively more bandwidth expansion and run again */\n                SKP_Silk_bwexpander_32( a_Q16, d, 65536 - SKP_SMULBB( 10 + i, i ) ); // 10_Q16 = 0.00015\n\n                SKP_Silk_A2NLSF_init( a_Q16, P, Q, dd );\n                p = P;                            /* Pointer to polynomial */\n                xlo = SKP_Silk_LSFCosTab_FIX_Q12[ 0 ]; // Q12\n                ylo = SKP_Silk_A2NLSF_eval_poly( p, xlo, dd );\n                if( ylo < 0 ) {\n                    /* Set the first NLSF to zero and move on to the next */\n                    NLSF[ 0 ] = 0;\n                    p = Q;                        /* Pointer to polynomial */\n                    ylo = SKP_Silk_A2NLSF_eval_poly( p, xlo, dd );\n                    root_ix = 1;                  /* Index of current root */\n                } else {\n                    root_ix = 0;                  /* Index of current root */\n                }\n                k = 1;                            /* Reset loop counter */\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_CNG.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n/* Generates excitation for CNG LPC synthesis */\nSKP_INLINE void SKP_Silk_CNG_exc(\n    SKP_int16                       residual[],         /* O    CNG residual signal Q0                      */\n    SKP_int32                       exc_buf_Q10[],      /* I    Random samples buffer Q10                   */\n    SKP_int32                       Gain_Q16,           /* I    Gain to apply                               */\n    SKP_int                         length,             /* I    Length                                      */\n    SKP_int32                       *rand_seed          /* I/O  Seed to random index generator              */\n)\n{\n    SKP_int32 seed;\n    SKP_int   i, idx, exc_mask;\n\n    exc_mask = CNG_BUF_MASK_MAX;\n    while( exc_mask > length ) {\n        exc_mask = SKP_RSHIFT( exc_mask, 1 );\n    }\n\n    seed = *rand_seed;\n    for( i = 0; i < length; i++ ) {\n        seed = SKP_RAND( seed );\n        idx = ( SKP_int )( SKP_RSHIFT( seed, 24 ) & exc_mask );\n        SKP_assert( idx >= 0 );\n        SKP_assert( idx <= CNG_BUF_MASK_MAX );\n        residual[ i ] = ( SKP_int16 )SKP_SAT16( SKP_RSHIFT_ROUND( SKP_SMULWW( exc_buf_Q10[ idx ], Gain_Q16 ), 10 ) );\n    }\n    *rand_seed = seed;\n}\n\nvoid SKP_Silk_CNG_Reset(\n    SKP_Silk_decoder_state      *psDec              /* I/O  Decoder state                               */\n)\n{\n    SKP_int i, NLSF_step_Q15, NLSF_acc_Q15;\n\n    NLSF_step_Q15 = SKP_DIV32_16( SKP_int16_MAX, psDec->LPC_order + 1 );\n    NLSF_acc_Q15 = 0;\n    for( i = 0; i < psDec->LPC_order; i++ ) {\n        NLSF_acc_Q15 += NLSF_step_Q15;\n        psDec->sCNG.CNG_smth_NLSF_Q15[ i ] = NLSF_acc_Q15;\n    }\n    psDec->sCNG.CNG_smth_Gain_Q16 = 0;\n    psDec->sCNG.rand_seed = 3176576;\n}\n\n/* Updates CNG estimate, and applies the CNG when packet was lost   */\nvoid SKP_Silk_CNG(\n    SKP_Silk_decoder_state      *psDec,             /* I/O  Decoder state                               */\n    SKP_Silk_decoder_control    *psDecCtrl,         /* I/O  Decoder control                             */\n    SKP_int16                   signal[],           /* I/O  Signal                                      */\n    SKP_int                     length              /* I    Length of residual                          */\n)\n{\n    SKP_int   i, subfr;\n    SKP_int32 tmp_32, Gain_Q26, max_Gain_Q16;\n    SKP_int16 LPC_buf[ MAX_LPC_ORDER ];\n    SKP_int16 CNG_sig[ MAX_FRAME_LENGTH ];\n    SKP_Silk_CNG_struct *psCNG;\n    psCNG = &psDec->sCNG;\n\n    if( psDec->fs_kHz != psCNG->fs_kHz ) {\n        /* Reset state */\n        SKP_Silk_CNG_Reset( psDec );\n\n        psCNG->fs_kHz = psDec->fs_kHz;\n    }\n    if( psDec->lossCnt == 0 && psDec->vadFlag == NO_VOICE_ACTIVITY ) {\n        /* Update CNG parameters */\n\n        /* Smoothing of LSF's  */\n        for( i = 0; i < psDec->LPC_order; i++ ) {\n            psCNG->CNG_smth_NLSF_Q15[ i ] += SKP_SMULWB( psDec->prevNLSF_Q15[ i ] - psCNG->CNG_smth_NLSF_Q15[ i ], CNG_NLSF_SMTH_Q16 );\n        }\n        /* Find the subframe with the highest gain */\n        max_Gain_Q16 = 0;\n        subfr        = 0;\n        for( i = 0; i < NB_SUBFR; i++ ) {\n            if( psDecCtrl->Gains_Q16[ i ] > max_Gain_Q16 ) {\n                max_Gain_Q16 = psDecCtrl->Gains_Q16[ i ];\n                subfr        = i;\n            }\n        }\n        /* Update CNG excitation buffer with excitation from this subframe */\n        SKP_memmove( &psCNG->CNG_exc_buf_Q10[ psDec->subfr_length ], psCNG->CNG_exc_buf_Q10, ( NB_SUBFR - 1 ) * psDec->subfr_length * sizeof( SKP_int32 ) );\n        SKP_memcpy(   psCNG->CNG_exc_buf_Q10, &psDec->exc_Q10[ subfr * psDec->subfr_length ], psDec->subfr_length * sizeof( SKP_int32 ) );\n\n        /* Smooth gains */\n        for( i = 0; i < NB_SUBFR; i++ ) {\n            psCNG->CNG_smth_Gain_Q16 += SKP_SMULWB( psDecCtrl->Gains_Q16[ i ] - psCNG->CNG_smth_Gain_Q16, CNG_GAIN_SMTH_Q16 );\n        }\n    }\n\n    /* Add CNG when packet is lost and / or when low speech activity */\n    if( psDec->lossCnt ) {//|| psDec->vadFlag == NO_VOICE_ACTIVITY ) {\n\n        /* Generate CNG excitation */\n        SKP_Silk_CNG_exc( CNG_sig, psCNG->CNG_exc_buf_Q10, \n                psCNG->CNG_smth_Gain_Q16, length, &psCNG->rand_seed );\n\n        /* Convert CNG NLSF to filter representation */\n        SKP_Silk_NLSF2A_stable( LPC_buf, psCNG->CNG_smth_NLSF_Q15, psDec->LPC_order );\n\n        Gain_Q26 = ( SKP_int32 )1 << 26; /* 1.0 */\n        \n        /* Generate CNG signal, by synthesis filtering */\n        if( psDec->LPC_order == 16 ) {\n            SKP_Silk_LPC_synthesis_order16( CNG_sig, LPC_buf, \n                Gain_Q26, psCNG->CNG_synth_state, CNG_sig, length );\n        } else {\n            SKP_Silk_LPC_synthesis_filter( CNG_sig, LPC_buf, \n                Gain_Q26, psCNG->CNG_synth_state, CNG_sig, length, psDec->LPC_order );\n        }\n        /* Mix with signal */\n        for( i = 0; i < length; i++ ) {\n            tmp_32 = signal[ i ] + CNG_sig[ i ];\n            signal[ i ] = SKP_SAT16( tmp_32 );\n        }\n    } else {\n        SKP_memset( psCNG->CNG_synth_state, 0, psDec->LPC_order *  sizeof( SKP_int32 ) );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_HP_variable_cutoff_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n#include \"SKP_Silk_tuning_parameters.h\"\n\n#if HIGH_PASS_INPUT\n\n#define SKP_RADIANS_CONSTANT_Q19            1482    // 0.45f * 2.0f * 3.14159265359 / 1000\n#define SKP_LOG2_VARIABLE_HP_MIN_FREQ_Q7    809     // log(80) in Q7\n\n/* High-pass filter with cutoff frequency adaptation based on pitch lag statistics */\nvoid SKP_Silk_HP_variable_cutoff_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,             /* I/O  Encoder state FIX                           */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl,         /* I/O  Encoder control FIX                         */\n    SKP_int16                       *out,               /* O    high-pass filtered output signal            */\n    const SKP_int16                 *in                 /* I    input signal                                */\n)\n{\n    SKP_int   quality_Q15;\n    SKP_int32 B_Q28[ 3 ], A_Q28[ 2 ];\n    SKP_int32 Fc_Q19, r_Q28, r_Q22;\n    SKP_int32 pitch_freq_Hz_Q16, pitch_freq_log_Q7, delta_freq_Q7;\n\n    /*********************************************/\n    /* Estimate Low End of Pitch Frequency Range */\n    /*********************************************/\n    if( psEnc->sCmn.prev_sigtype == SIG_TYPE_VOICED ) {\n        /* difference, in log domain */\n        pitch_freq_Hz_Q16 = SKP_DIV32_16( SKP_LSHIFT( SKP_MUL( psEnc->sCmn.fs_kHz, 1000 ), 16 ), psEnc->sCmn.prevLag );\n        pitch_freq_log_Q7 = SKP_Silk_lin2log( pitch_freq_Hz_Q16 ) - ( 16 << 7 ); //0x70\n\n        /* adjustment based on quality */\n        quality_Q15 = psEncCtrl->input_quality_bands_Q15[ 0 ];\n        pitch_freq_log_Q7 = SKP_SUB32( pitch_freq_log_Q7, SKP_SMULWB( SKP_SMULWB( SKP_LSHIFT( quality_Q15, 2 ), quality_Q15 ), \n            pitch_freq_log_Q7 - SKP_LOG2_VARIABLE_HP_MIN_FREQ_Q7 ) );\n        pitch_freq_log_Q7 = SKP_ADD32( pitch_freq_log_Q7, SKP_RSHIFT( SKP_FIX_CONST( 0.6, 15 ) - quality_Q15, 9 ) );\n\n        //delta_freq = pitch_freq_log - psEnc->variable_HP_smth1;\n        delta_freq_Q7 = pitch_freq_log_Q7 - SKP_RSHIFT( psEnc->variable_HP_smth1_Q15, 8 );\n        if( delta_freq_Q7 < 0 ) {\n            /* less smoothing for decreasing pitch frequency, to track something close to the minimum */\n            delta_freq_Q7 = SKP_MUL( delta_freq_Q7, 3 );\n        }\n\n        /* limit delta, to reduce impact of outliers */\n        delta_freq_Q7 = SKP_LIMIT_32( delta_freq_Q7, -SKP_FIX_CONST( VARIABLE_HP_MAX_DELTA_FREQ, 7 ), SKP_FIX_CONST( VARIABLE_HP_MAX_DELTA_FREQ, 7 ) );\n\n        /* update smoother */\n        psEnc->variable_HP_smth1_Q15 = SKP_SMLAWB( psEnc->variable_HP_smth1_Q15, \n            SKP_MUL( SKP_LSHIFT( psEnc->speech_activity_Q8, 1 ), delta_freq_Q7 ), SKP_FIX_CONST( VARIABLE_HP_SMTH_COEF1, 16 ) );\n    }\n    /* second smoother */\n    psEnc->variable_HP_smth2_Q15 = SKP_SMLAWB( psEnc->variable_HP_smth2_Q15, \n        psEnc->variable_HP_smth1_Q15 - psEnc->variable_HP_smth2_Q15, SKP_FIX_CONST( VARIABLE_HP_SMTH_COEF2, 16 ) );\n\n    /* convert from log scale to Hertz */\n    psEncCtrl->pitch_freq_low_Hz = SKP_Silk_log2lin( SKP_RSHIFT( psEnc->variable_HP_smth2_Q15, 8 ) );\n\n    /* limit frequency range */\n    psEncCtrl->pitch_freq_low_Hz = SKP_LIMIT_32( psEncCtrl->pitch_freq_low_Hz, \n        SKP_FIX_CONST( VARIABLE_HP_MIN_FREQ, 0 ), SKP_FIX_CONST( VARIABLE_HP_MAX_FREQ, 0 ) );\n\n    /********************************/\n    /* Compute Filter Coefficients  */\n    /********************************/\n    /* compute cut-off frequency, in radians */\n    //Fc_num   = (SKP_float)( 0.45f * 2.0f * 3.14159265359 * psEncCtrl->pitch_freq_low_Hz );\n    //Fc_denom = (SKP_float)( 1e3f * psEnc->sCmn.fs_kHz );\n    SKP_assert( psEncCtrl->pitch_freq_low_Hz <= SKP_int32_MAX / SKP_RADIANS_CONSTANT_Q19 );\n    Fc_Q19 = SKP_DIV32_16( SKP_SMULBB( SKP_RADIANS_CONSTANT_Q19, psEncCtrl->pitch_freq_low_Hz ), psEnc->sCmn.fs_kHz ); // range: 3704 - 27787, 11-15 bits\n    SKP_assert( Fc_Q19 >=  3704 );\n    SKP_assert( Fc_Q19 <= 27787 );\n\n    r_Q28 = SKP_FIX_CONST( 1.0, 28 ) - SKP_MUL( SKP_FIX_CONST( 0.92, 9 ), Fc_Q19 );\n    SKP_assert( r_Q28 >= 255347779 );\n    SKP_assert( r_Q28 <= 266690872 );\n\n    /* b = r * [ 1; -2; 1 ]; */\n    /* a = [ 1; -2 * r * ( 1 - 0.5 * Fc^2 ); r^2 ]; */\n    B_Q28[ 0 ] = r_Q28;\n    B_Q28[ 1 ] = SKP_LSHIFT( -r_Q28, 1 );\n    B_Q28[ 2 ] = r_Q28;\n    \n    // -r * ( 2 - Fc * Fc );\n    r_Q22  = SKP_RSHIFT( r_Q28, 6 );\n    A_Q28[ 0 ] = SKP_SMULWW( r_Q22, SKP_SMULWW( Fc_Q19, Fc_Q19 ) - SKP_FIX_CONST( 2.0,  22 ) );\n    A_Q28[ 1 ] = SKP_SMULWW( r_Q22, r_Q22 );\n\n    /********************************/\n    /* High-Pass Filter             */\n    /********************************/\n    SKP_Silk_biquad_alt( in, B_Q28, A_Q28, psEnc->sCmn.In_HP_State, out, psEnc->sCmn.frame_length );\n}\n\n#endif // HIGH_PASS_INPUT\n"
  },
  {
    "path": "app/jni/SKP_Silk_LBRR_reset.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n/* Resets LBRR buffer, used if packet size changes */\nvoid SKP_Silk_LBRR_reset( \n    SKP_Silk_encoder_state      *psEncC             /* I/O  state                                       */\n)\n{\n    SKP_int i;\n\n    for( i = 0; i < MAX_LBRR_DELAY; i++ ) {\n        psEncC->LBRR_buffer[ i ].usage = SKP_SILK_NO_LBRR;\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_LPC_inv_pred_gain.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_LPC_inverse_pred_gain.c                                   *\n *                                                                      *\n * Compute inverse of LPC prediction gain, and                          *\n * test if LPC coefficients are stable (all poles within unit circle)   *\n *                                                                      *\n * Copyright 2008 (c), Skype Limited                                    *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n#define QA          16\n#define A_LIMIT     SKP_FIX_CONST( 0.99975, QA )\n\n/* Compute inverse of LPC prediction gain, and                          */\n/* test if LPC coefficients are stable (all poles within unit circle)   */\nstatic SKP_int LPC_inverse_pred_gain_QA(        /* O:   Returns 1 if unstable, otherwise 0          */\n    SKP_int32           *invGain_Q30,           /* O:   Inverse prediction gain, Q30 energy domain  */\n    SKP_int32           A_QA[ 2 ][ SKP_Silk_MAX_ORDER_LPC ],         \n                                                /* I:   Prediction coefficients                     */\n    const SKP_int       order                   /* I:   Prediction order                            */\n)\n{\n    SKP_int   k, n, headrm;\n    SKP_int32 rc_Q31, rc_mult1_Q30, rc_mult2_Q16, tmp_QA;\n    SKP_int32 *Aold_QA, *Anew_QA;\n\n    Anew_QA = A_QA[ order & 1 ];\n\n    *invGain_Q30 = ( 1 << 30 );\n    for( k = order - 1; k > 0; k-- ) {\n        /* Check for stability */\n        if( ( Anew_QA[ k ] > A_LIMIT ) || ( Anew_QA[ k ] < -A_LIMIT ) ) {\n            return 1;\n        }\n\n        /* Set RC equal to negated AR coef */\n        rc_Q31 = -SKP_LSHIFT( Anew_QA[ k ], 31 - QA );\n        \n        /* rc_mult1_Q30 range: [ 1 : 2^30-1 ] */\n        rc_mult1_Q30 = ( SKP_int32_MAX >> 1 ) - SKP_SMMUL( rc_Q31, rc_Q31 );\n        SKP_assert( rc_mult1_Q30 > ( 1 << 15 ) );                   /* reduce A_LIMIT if fails */\n        SKP_assert( rc_mult1_Q30 < ( 1 << 30 ) );\n\n        /* rc_mult2_Q16 range: [ 2^16 : SKP_int32_MAX ] */\n        rc_mult2_Q16 = SKP_INVERSE32_varQ( rc_mult1_Q30, 46 );      /* 16 = 46 - 30 */\n\n        /* Update inverse gain */\n        /* invGain_Q30 range: [ 0 : 2^30 ] */\n        *invGain_Q30 = SKP_LSHIFT( SKP_SMMUL( *invGain_Q30, rc_mult1_Q30 ), 2 );\n        SKP_assert( *invGain_Q30 >= 0           );\n        SKP_assert( *invGain_Q30 <= ( 1 << 30 ) );\n\n        /* Swap pointers */\n        Aold_QA = Anew_QA;\n        Anew_QA = A_QA[ k & 1 ];\n        \n        /* Update AR coefficient */\n        headrm = SKP_Silk_CLZ32( rc_mult2_Q16 ) - 1;\n        rc_mult2_Q16 = SKP_LSHIFT( rc_mult2_Q16, headrm );          /* Q: 16 + headrm */\n        for( n = 0; n < k; n++ ) {\n            tmp_QA = Aold_QA[ n ] - SKP_LSHIFT( SKP_SMMUL( Aold_QA[ k - n - 1 ], rc_Q31 ), 1 );\n            Anew_QA[ n ] = SKP_LSHIFT( SKP_SMMUL( tmp_QA, rc_mult2_Q16 ), 16 - headrm );\n        }\n    }\n\n    /* Check for stability */\n    if( ( Anew_QA[ 0 ] > A_LIMIT ) || ( Anew_QA[ 0 ] < -A_LIMIT ) ) {\n        return 1;\n    }\n\n    /* Set RC equal to negated AR coef */\n    rc_Q31 = -SKP_LSHIFT( Anew_QA[ 0 ], 31 - QA );\n\n    /* Range: [ 1 : 2^30 ] */\n    rc_mult1_Q30 = ( SKP_int32_MAX >> 1 ) - SKP_SMMUL( rc_Q31, rc_Q31 );\n\n    /* Update inverse gain */\n    /* Range: [ 0 : 2^30 ] */\n    *invGain_Q30 = SKP_LSHIFT( SKP_SMMUL( *invGain_Q30, rc_mult1_Q30 ), 2 );\n    SKP_assert( *invGain_Q30 >= 0     );\n    SKP_assert( *invGain_Q30 <= 1<<30 );\n\n    return 0;\n}\n/* For input in Q12 domain */\nSKP_int SKP_Silk_LPC_inverse_pred_gain(       /* O:   Returns 1 if unstable, otherwise 0          */\n    SKP_int32           *invGain_Q30,           /* O:   Inverse prediction gain, Q30 energy domain  */\n    const SKP_int16     *A_Q12,                 /* I:   Prediction coefficients, Q12 [order]        */\n    const SKP_int       order                   /* I:   Prediction order                            */\n)\n{\n    SKP_int   k;\n    SKP_int32 Atmp_QA[ 2 ][ SKP_Silk_MAX_ORDER_LPC ];\n    SKP_int32 *Anew_QA;\n\n    Anew_QA = Atmp_QA[ order & 1 ];\n\n    /* Increase Q domain of the AR coefficients */\n    for( k = 0; k < order; k++ ) {\n        Anew_QA[ k ] = SKP_LSHIFT( (SKP_int32)A_Q12[ k ], QA - 12 );\n    }\n\n    return LPC_inverse_pred_gain_QA( invGain_Q30, Atmp_QA, order );\n}\n\n/* For input in Q24 domain */\nSKP_int SKP_Silk_LPC_inverse_pred_gain_Q24(   /* O:   Returns 1 if unstable, otherwise 0          */\n    SKP_int32           *invGain_Q30,           /* O:   Inverse prediction gain, Q30 energy domain  */\n    const SKP_int32     *A_Q24,                 /* I:   Prediction coefficients, Q24 [order]        */\n    const SKP_int       order                   /* I:   Prediction order                            */\n)\n{\n    SKP_int   k;\n    SKP_int32 Atmp_QA[ 2 ][ SKP_Silk_MAX_ORDER_LPC ];\n    SKP_int32 *Anew_QA;\n\n    Anew_QA = Atmp_QA[ order & 1 ];\n\n    /* Increase Q domain of the AR coefficients */\n    for( k = 0; k < order; k++ ) {\n        Anew_QA[ k ] = SKP_RSHIFT_ROUND( A_Q24[ k ], 24 - QA );\n    }\n\n    return LPC_inverse_pred_gain_QA( invGain_Q30, Atmp_QA, order );\n}\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_LPC_synthesis_filter.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_LPC_synthesis_filter.c                                    *\n * Coefficients are in Q12                                              *\n *                                                                      *\n * even order AR filter                                                 *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* even order AR filter */\nvoid SKP_Silk_LPC_synthesis_filter(\n    const SKP_int16 *in,        /* I:   excitation signal */\n    const SKP_int16 *A_Q12,     /* I:   AR coefficients [Order], between -8_Q0 and 8_Q0 */\n    const SKP_int32 Gain_Q26,   /* I:   gain */\n    SKP_int32 *S,               /* I/O: state vector [Order] */\n    SKP_int16 *out,             /* O:   output signal */\n    const SKP_int32 len,        /* I:   signal length */\n    const SKP_int Order         /* I:   filter order, must be even */\n)\n{\n    SKP_int   k, j, idx, Order_half = SKP_RSHIFT( Order, 1 );\n    SKP_int32 SA, SB, out32_Q10, out32;\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n    SKP_int32 Atmp, A_align_Q12[ SKP_Silk_MAX_ORDER_LPC >> 1 ];\n\n    /* combine two A_Q12 values and ensure 32-bit alignment */\n    for( k = 0; k < Order_half; k++ ) {\n        idx = SKP_SMULBB( 2, k );\n        A_align_Q12[ k ] = ( ( ( SKP_int32 )A_Q12[ idx ] ) & 0x0000ffff ) | SKP_LSHIFT( ( SKP_int32 )A_Q12[ idx + 1 ], 16 );\n    }\n#endif\n\n    /* Order must be even */\n    SKP_assert( 2 * Order_half == Order );\n\n    /* S[] values are in Q14 */\n    for( k = 0; k < len; k++ ) {\n        SA = S[ Order - 1 ];\n        out32_Q10 = 0;\n        for( j = 0; j < ( Order_half - 1 ); j++ ) {\n            idx = SKP_SMULBB( 2, j ) + 1;\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n            /* multiply-add two prediction coefficients for each loop */\n            /* NOTE: the code below loads two int16 values in an int32, and multiplies each using the   */\n            /* SMLAWB and SMLAWT instructions. On a big-endian CPU the two int16 variables would be     */\n            /* loaded in reverse order and the code will give the wrong result. In that case swapping   */\n            /* the SMLAWB and SMLAWT instructions should solve the problem.                             */\n            Atmp = A_align_Q12[ j ];\n            SB = S[ Order - 1 - idx ];\n            S[ Order - 1 - idx ] = SA;\n            out32_Q10 = SKP_SMLAWB( out32_Q10, SA, Atmp );\n            out32_Q10 = SKP_SMLAWT( out32_Q10, SB, Atmp );\n            SA = S[ Order - 2 - idx ];\n            S[ Order - 2 - idx ] = SB;\n#else\n            SB = S[ Order - 1 - idx ];\n            S[ Order - 1 - idx ] = SA;\n            out32_Q10 = SKP_SMLAWB( out32_Q10, SA, A_Q12[ ( j << 1 ) ] );\n            out32_Q10 = SKP_SMLAWB( out32_Q10, SB, A_Q12[ ( j << 1 ) + 1 ] );\n            SA = S[ Order - 2 - idx ];\n            S[ Order - 2 - idx ] = SB;\n#endif\n        }\n\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n        /* unrolled loop: epilog */\n        Atmp = A_align_Q12[ Order_half - 1 ];\n        SB = S[ 0 ];\n        S[ 0 ] = SA;\n        out32_Q10 = SKP_SMLAWB( out32_Q10, SA, Atmp );\n        out32_Q10 = SKP_SMLAWT( out32_Q10, SB, Atmp );\n#else\n        /* unrolled loop: epilog */\n        SB = S[ 0 ];\n        S[ 0 ] = SA;\n        out32_Q10 = SKP_SMLAWB( out32_Q10, SA, A_Q12[ Order - 2 ] );\n        out32_Q10 = SKP_SMLAWB( out32_Q10, SB, A_Q12[ Order - 1 ] );\n#endif\n        /* apply gain to excitation signal and add to prediction */\n        out32_Q10 = SKP_ADD_SAT32( out32_Q10, SKP_SMULWB( Gain_Q26, in[ k ] ) );\n\n        /* scale to Q0 */\n        out32 = SKP_RSHIFT_ROUND( out32_Q10, 10 );\n\n        /* saturate output */\n        out[ k ] = ( SKP_int16 )SKP_SAT16( out32 );\n\n        /* move result into delay line */\n        S[ Order - 1 ] = SKP_LSHIFT_SAT32( out32_Q10, 4 );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_LPC_synthesis_order16.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_LPC_synthesis_order16.c                                   *\n * Coefficients are in Q12                                              *\n *                                                                      *\n * 16th order AR filter                                                 *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* 16th order AR filter */\nvoid SKP_Silk_LPC_synthesis_order16(const SKP_int16 *in,          /* I:   excitation signal */\n                                      const SKP_int16 *A_Q12,       /* I:   AR coefficients [16], between -8_Q0 and 8_Q0 */\n                                      const SKP_int32 Gain_Q26,     /* I:   gain */\n                                      SKP_int32 *S,                 /* I/O: state vector [16] */\n                                      SKP_int16 *out,               /* O:   output signal */\n                                      const SKP_int32 len           /* I:   signal length, must be multiple of 16 */\n)\n{\n    SKP_int   k;\n    SKP_int32 SA, SB, out32_Q10, out32;\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n    SKP_int32 Atmp, A_align_Q12[ 8 ];\n    /* combine two A_Q12 values and ensure 32-bit alignment */\n    for( k = 0; k < 8; k++ ) {\n        A_align_Q12[ k ] = ( ( ( SKP_int32 )A_Q12[ 2 * k ] ) & 0x0000ffff ) | SKP_LSHIFT( ( SKP_int32 )A_Q12[ 2 * k + 1 ], 16 );\n    }\n    /* S[] values are in Q14 */\n    /* NOTE: the code below loads two int16 values in an int32, and multiplies each using the   */\n    /* SMLAWB and SMLAWT instructions. On a big-endian CPU the two int16 variables would be     */\n    /* loaded in reverse order and the code will give the wrong result. In that case swapping   */\n    /* the SMLAWB and SMLAWT instructions should solve the problem.                             */\n    for( k = 0; k < len; k++ ) {\n        /* unrolled loop: prolog */\n        /* multiply-add two prediction coefficients per iteration */\n        SA = S[ 15 ];\n        Atmp = A_align_Q12[ 0 ];\n        SB = S[ 14 ];\n        S[ 14 ] = SA;\n        out32_Q10 = SKP_SMULWB(                  SA, Atmp );\n        out32_Q10 = SKP_SMLAWT_ovflw( out32_Q10, SB, Atmp );\n        SA = S[ 13 ];\n        S[ 13 ] = SB;\n\n        /* unrolled loop: main loop */\n        Atmp = A_align_Q12[ 1 ];\n        SB = S[ 12 ];\n        S[ 12 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, Atmp );\n        out32_Q10 = SKP_SMLAWT_ovflw( out32_Q10, SB, Atmp );\n        SA = S[ 11 ];\n        S[ 11 ] = SB;\n\n        Atmp = A_align_Q12[ 2 ];\n        SB = S[ 10 ];\n        S[ 10 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, Atmp );\n        out32_Q10 = SKP_SMLAWT_ovflw( out32_Q10, SB, Atmp );\n        SA = S[ 9 ];\n        S[ 9 ] = SB;\n\n        Atmp = A_align_Q12[ 3 ];\n        SB = S[ 8 ];\n        S[ 8 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, Atmp );\n        out32_Q10 = SKP_SMLAWT_ovflw( out32_Q10, SB, Atmp );\n        SA = S[ 7 ];\n        S[ 7 ] = SB;\n\n        Atmp = A_align_Q12[ 4 ];\n        SB = S[ 6 ];\n        S[ 6 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, Atmp );\n        out32_Q10 = SKP_SMLAWT_ovflw( out32_Q10, SB, Atmp );\n        SA = S[ 5 ];\n        S[ 5 ] = SB;\n\n        Atmp = A_align_Q12[ 5 ];\n        SB = S[ 4 ];\n        S[ 4 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, Atmp );\n        out32_Q10 = SKP_SMLAWT_ovflw( out32_Q10, SB, Atmp );\n        SA = S[ 3 ];\n        S[ 3 ] = SB;\n\n        Atmp = A_align_Q12[ 6 ];\n        SB = S[ 2 ];\n        S[ 2 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, Atmp );\n        out32_Q10 = SKP_SMLAWT_ovflw( out32_Q10, SB, Atmp );\n        SA = S[ 1 ];\n        S[ 1 ] = SB;\n\n        /* unrolled loop: epilog */\n        Atmp = A_align_Q12[ 7 ];\n        SB = S[ 0 ];\n        S[ 0 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, Atmp );\n        out32_Q10 = SKP_SMLAWT_ovflw( out32_Q10, SB, Atmp );\n\n        /* unrolled loop: end */\n        /* apply gain to excitation signal and add to prediction */\n        out32_Q10 = SKP_ADD_SAT32( out32_Q10, SKP_SMULWB( Gain_Q26, in[ k ] ) );\n\n        /* scale to Q0 */\n        out32 = SKP_RSHIFT_ROUND( out32_Q10, 10 );\n\n        /* saturate output */\n        out[ k ] = ( SKP_int16 )SKP_SAT16( out32 );\n\n        /* move result into delay line */\n        S[ 15 ] = SKP_LSHIFT_SAT32( out32_Q10, 4 );\n    }\n#else\n    for( k = 0; k < len; k++ ) {\n        /* unrolled loop: prolog */\n        /* multiply-add two prediction coefficients per iteration */\n        SA = S[ 15 ];\n        SB = S[ 14 ];\n        S[ 14 ] = SA;\n        out32_Q10 = SKP_SMULWB(                  SA, A_Q12[ 0 ] );\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SB, A_Q12[ 1 ] );\n        SA = S[ 13 ];\n        S[ 13 ] = SB;\n\n        /* unrolled loop: main loop */\n        SB = S[ 12 ];\n        S[ 12 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, A_Q12[ 2 ] );\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SB, A_Q12[ 3 ] );\n        SA = S[ 11 ];\n        S[ 11 ] = SB;\n\n        SB = S[ 10 ];\n        S[ 10 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, A_Q12[ 4 ] );\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SB, A_Q12[ 5 ] );\n        SA = S[ 9 ];\n        S[ 9 ] = SB;\n\n        SB = S[ 8 ];\n        S[ 8 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, A_Q12[ 6 ] );\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SB, A_Q12[ 7 ] );\n        SA = S[ 7 ];\n        S[ 7 ] = SB;\n\n        SB = S[ 6 ];\n        S[ 6 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, A_Q12[ 8 ] );\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SB, A_Q12[ 9 ] );\n        SA = S[ 5 ];\n        S[ 5 ] = SB;\n\n        SB = S[ 4 ];\n        S[ 4 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, A_Q12[ 10 ] );\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SB, A_Q12[ 11 ] );\n        SA = S[ 3 ];\n        S[ 3 ] = SB;\n\n        SB = S[ 2 ];\n        S[ 2 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, A_Q12[ 12 ] );\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SB, A_Q12[ 13 ] );\n        SA = S[ 1 ];\n        S[ 1 ] = SB;\n\n        /* unrolled loop: epilog */\n        SB = S[ 0 ];\n        S[ 0 ] = SA;\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SA, A_Q12[ 14 ] );\n        out32_Q10 = SKP_SMLAWB_ovflw( out32_Q10, SB, A_Q12[ 15 ] );\n\n        /* unrolled loop: end */\n        /* apply gain to excitation signal and add to prediction */\n        out32_Q10 = SKP_ADD_SAT32( out32_Q10, SKP_SMULWB( Gain_Q26, in[ k ] ) );\n\n        /* scale to Q0 */\n        out32 = SKP_RSHIFT_ROUND( out32_Q10, 10 );\n\n        /* saturate output */\n        out[ k ] = ( SKP_int16 )SKP_SAT16( out32 );\n\n        /* move result into delay line */\n        S[ 15 ] = SKP_LSHIFT_SAT32( out32_Q10, 4 );\n    }\n#endif\n}\n\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_LP_variable_cutoff.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/* \n\n    Elliptic/Cauer filters designed with 0.1 dB passband ripple, \n        80 dB minimum stopband attenuation, and\n        [0.95 : 0.15 : 0.35] normalized cut off frequencies.\n\n*/\n#include \"SKP_Silk_main.h\"\n\n#if SWITCH_TRANSITION_FILTERING\n\n/* Helper function, that interpolates the filter taps */\nSKP_INLINE void SKP_Silk_LP_interpolate_filter_taps( \n    SKP_int32           B_Q28[ TRANSITION_NB ], \n    SKP_int32           A_Q28[ TRANSITION_NA ],\n    const SKP_int       ind,\n    const SKP_int32     fac_Q16\n)\n{\n    SKP_int nb, na;\n\n    if( ind < TRANSITION_INT_NUM - 1 ) {\n        if( fac_Q16 > 0 ) {\n            if( fac_Q16 == SKP_SAT16( fac_Q16 ) ) { /* fac_Q16 is in range of a 16-bit int */\n                /* Piece-wise linear interpolation of B and A */\n                for( nb = 0; nb < TRANSITION_NB; nb++ ) {\n                    B_Q28[ nb ] = SKP_SMLAWB(\n                        SKP_Silk_Transition_LP_B_Q28[ ind     ][ nb ],\n                        SKP_Silk_Transition_LP_B_Q28[ ind + 1 ][ nb ] -\n                        SKP_Silk_Transition_LP_B_Q28[ ind     ][ nb ],\n                        fac_Q16 );\n                }\n                for( na = 0; na < TRANSITION_NA; na++ ) {\n                    A_Q28[ na ] = SKP_SMLAWB(\n                        SKP_Silk_Transition_LP_A_Q28[ ind     ][ na ],\n                        SKP_Silk_Transition_LP_A_Q28[ ind + 1 ][ na ] -\n                        SKP_Silk_Transition_LP_A_Q28[ ind     ][ na ],\n                        fac_Q16 );\n                }\n            } else if( fac_Q16 == ( 1 << 15 ) ) { /* Neither fac_Q16 nor ( ( 1 << 16 ) - fac_Q16 ) is in range of a 16-bit int */\n\n                /* Piece-wise linear interpolation of B and A */\n                for( nb = 0; nb < TRANSITION_NB; nb++ ) {\n                    B_Q28[ nb ] = SKP_RSHIFT( \n                        SKP_Silk_Transition_LP_B_Q28[ ind     ][ nb ] +\n                        SKP_Silk_Transition_LP_B_Q28[ ind + 1 ][ nb ],\n                        1 );\n                }\n                for( na = 0; na < TRANSITION_NA; na++ ) {\n                    A_Q28[ na ] = SKP_RSHIFT( \n                        SKP_Silk_Transition_LP_A_Q28[ ind     ][ na ] + \n                        SKP_Silk_Transition_LP_A_Q28[ ind + 1 ][ na ], \n                        1 );\n                }\n            } else { /* ( ( 1 << 16 ) - fac_Q16 ) is in range of a 16-bit int */\n                \n                SKP_assert( ( ( 1 << 16 ) - fac_Q16 ) == SKP_SAT16( ( ( 1 << 16 ) - fac_Q16) ) );\n                /* Piece-wise linear interpolation of B and A */\n                for( nb = 0; nb < TRANSITION_NB; nb++ ) {\n                    B_Q28[ nb ] = SKP_SMLAWB(\n                        SKP_Silk_Transition_LP_B_Q28[ ind + 1 ][ nb ],\n                        SKP_Silk_Transition_LP_B_Q28[ ind     ][ nb ] -\n                        SKP_Silk_Transition_LP_B_Q28[ ind + 1 ][ nb ],\n                        ( 1 << 16 ) - fac_Q16 );\n                }\n                for( na = 0; na < TRANSITION_NA; na++ ) {\n                    A_Q28[ na ] = SKP_SMLAWB(\n                        SKP_Silk_Transition_LP_A_Q28[ ind + 1 ][ na ],\n                        SKP_Silk_Transition_LP_A_Q28[ ind     ][ na ] -\n                        SKP_Silk_Transition_LP_A_Q28[ ind + 1 ][ na ],\n                        ( 1 << 16 ) - fac_Q16 );\n                }\n            }\n        } else {\n            SKP_memcpy( B_Q28, SKP_Silk_Transition_LP_B_Q28[ ind ], TRANSITION_NB * sizeof( SKP_int32 ) );\n            SKP_memcpy( A_Q28, SKP_Silk_Transition_LP_A_Q28[ ind ], TRANSITION_NA * sizeof( SKP_int32 ) );\n        }\n    } else {\n        SKP_memcpy( B_Q28, SKP_Silk_Transition_LP_B_Q28[ TRANSITION_INT_NUM - 1 ], TRANSITION_NB * sizeof( SKP_int32 ) );\n        SKP_memcpy( A_Q28, SKP_Silk_Transition_LP_A_Q28[ TRANSITION_INT_NUM - 1 ], TRANSITION_NA * sizeof( SKP_int32 ) );\n    }\n}\n\n/* Low-pass filter with variable cutoff frequency based on  */\n/* piece-wise linear interpolation between elliptic filters */\n/* Start by setting psEncC->transition_frame_no = 1;            */\n/* Deactivate by setting psEncC->transition_frame_no = 0;   */\nvoid SKP_Silk_LP_variable_cutoff(\n    SKP_Silk_LP_state               *psLP,          /* I/O  LP filter state                     */\n    SKP_int16                       *out,           /* O    Low-pass filtered output signal     */\n    const SKP_int16                 *in,            /* I    Input signal                        */\n    const SKP_int                   frame_length    /* I    Frame length                        */\n)\n{\n    SKP_int32   B_Q28[ TRANSITION_NB ], A_Q28[ TRANSITION_NA ], fac_Q16 = 0;\n    SKP_int     ind = 0;\n\n    SKP_assert( psLP->transition_frame_no >= 0 );\n    SKP_assert( ( ( ( psLP->transition_frame_no <= TRANSITION_FRAMES_DOWN ) && ( psLP->mode == 0 ) ) || \n                  ( ( psLP->transition_frame_no <= TRANSITION_FRAMES_UP   ) && ( psLP->mode == 1 ) ) ) );\n\n    /* Interpolate filter coefficients if needed */\n    if( psLP->transition_frame_no > 0 ) {\n        if( psLP->mode == 0 ) {\n            if( psLP->transition_frame_no < TRANSITION_FRAMES_DOWN ) {\n                /* Calculate index and interpolation factor for interpolation */\n#if( TRANSITION_INT_STEPS_DOWN == 32 )\n                fac_Q16 = SKP_LSHIFT( psLP->transition_frame_no, 16 - 5 );\n#else\n                fac_Q16 = SKP_DIV32_16( SKP_LSHIFT( psLP->transition_frame_no, 16 ), TRANSITION_INT_STEPS_DOWN );\n#endif\n                ind      = SKP_RSHIFT( fac_Q16, 16 );\n                fac_Q16 -= SKP_LSHIFT( ind, 16 );\n\n                SKP_assert( ind >= 0 );\n                SKP_assert( ind < TRANSITION_INT_NUM );\n\n                /* Interpolate filter coefficients */\n                SKP_Silk_LP_interpolate_filter_taps( B_Q28, A_Q28, ind, fac_Q16 );\n\n                /* Increment transition frame number for next frame */\n                psLP->transition_frame_no++;\n\n            } else {\n                SKP_assert( psLP->transition_frame_no == TRANSITION_FRAMES_DOWN );\n                /* End of transition phase */\n                SKP_Silk_LP_interpolate_filter_taps( B_Q28, A_Q28, TRANSITION_INT_NUM - 1, 0 );\n            }\n        } else {\n            SKP_assert( psLP->mode == 1 );\n            if( psLP->transition_frame_no < TRANSITION_FRAMES_UP ) {\n                /* Calculate index and interpolation factor for interpolation */\n#if( TRANSITION_INT_STEPS_UP == 64 )\n                fac_Q16 = SKP_LSHIFT( TRANSITION_FRAMES_UP - psLP->transition_frame_no, 16 - 6 );\n#else\n                fac_Q16 = SKP_DIV32_16( SKP_LSHIFT( TRANSITION_FRAMES_UP - psLP->transition_frame_no, 16 ), TRANSITION_INT_STEPS_UP );\n#endif\n                ind      = SKP_RSHIFT( fac_Q16, 16 );\n                fac_Q16 -= SKP_LSHIFT( ind, 16 );\n\n                SKP_assert( ind >= 0 );\n                SKP_assert( ind < TRANSITION_INT_NUM );\n\n                /* Interpolate filter coefficients */\n                SKP_Silk_LP_interpolate_filter_taps( B_Q28, A_Q28, ind, fac_Q16 );\n\n                /* Increment transition frame number for next frame */\n                psLP->transition_frame_no++;\n            \n            } else {\n                SKP_assert( psLP->transition_frame_no == TRANSITION_FRAMES_UP );\n                /* End of transition phase */\n                SKP_Silk_LP_interpolate_filter_taps( B_Q28, A_Q28, 0, 0 );\n            }\n        }\n    } \n    \n    if( psLP->transition_frame_no > 0 ) {\n        /* ARMA low-pass filtering */\n        SKP_assert( TRANSITION_NB == 3 && TRANSITION_NA == 2 );\n        SKP_Silk_biquad_alt( in, B_Q28, A_Q28, psLP->In_LP_State, out, frame_length );\n    } else {\n        /* Instead of using the filter, copy input directly to output */\n        SKP_memcpy( out, in, frame_length * sizeof( SKP_int16 ) );\n    }\n}\n#endif\n"
  },
  {
    "path": "app/jni/SKP_Silk_LSF_cos_table.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n// Q12 values (even)\nconst SKP_int SKP_Silk_LSFCosTab_FIX_Q12[LSF_COS_TAB_SZ_FIX + 1] = {\n            8192,             8190,             8182,             8170,     \n            8152,             8130,             8104,             8072,     \n            8034,             7994,             7946,             7896,     \n            7840,             7778,             7714,             7644,     \n            7568,             7490,             7406,             7318,     \n            7226,             7128,             7026,             6922,     \n            6812,             6698,             6580,             6458,     \n            6332,             6204,             6070,             5934,     \n            5792,             5648,             5502,             5352,     \n            5198,             5040,             4880,             4718,     \n            4552,             4382,             4212,             4038,     \n            3862,             3684,             3502,             3320,     \n            3136,             2948,             2760,             2570,     \n            2378,             2186,             1990,             1794,     \n            1598,             1400,             1202,             1002,     \n             802,              602,              402,              202,     \n               0,             -202,             -402,             -602,     \n            -802,            -1002,            -1202,            -1400,     \n           -1598,            -1794,            -1990,            -2186,     \n           -2378,            -2570,            -2760,            -2948,     \n           -3136,            -3320,            -3502,            -3684,     \n           -3862,            -4038,            -4212,            -4382,     \n           -4552,            -4718,            -4880,            -5040,     \n           -5198,            -5352,            -5502,            -5648,     \n           -5792,            -5934,            -6070,            -6204,     \n           -6332,            -6458,            -6580,            -6698,     \n           -6812,            -6922,            -7026,            -7128,     \n           -7226,            -7318,            -7406,            -7490,     \n           -7568,            -7644,            -7714,            -7778,     \n           -7840,            -7896,            -7946,            -7994,     \n           -8034,            -8072,            -8104,            -8130,     \n           -8152,            -8170,            -8182,            -8190,     \n           -8192\n};\n"
  },
  {
    "path": "app/jni/SKP_Silk_LTP_analysis_filter_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\nvoid SKP_Silk_LTP_analysis_filter_FIX(\n    SKP_int16       *LTP_res,                           /* O:   LTP residual signal of length NB_SUBFR * ( pre_length + subfr_length )  */\n    const SKP_int16 *x,                                 /* I:   Pointer to input signal with at least max( pitchL ) preceeding samples  */\n    const SKP_int16 LTPCoef_Q14[ LTP_ORDER * NB_SUBFR ],/* I:   LTP_ORDER LTP coefficients for each NB_SUBFR subframe                   */\n    const SKP_int   pitchL[ NB_SUBFR ],                 /* I:   Pitch lag, one for each subframe                                        */\n    const SKP_int32 invGains_Q16[ NB_SUBFR ],           /* I:   Inverse quantization gains, one for each subframe                       */\n    const SKP_int   subfr_length,                       /* I:   Length of each subframe                                                 */\n    const SKP_int   pre_length                          /* I:   Length of the preceeding samples starting at &x[0] for each subframe    */\n)\n{\n    const SKP_int16 *x_ptr, *x_lag_ptr;\n    SKP_int16   Btmp_Q14[ LTP_ORDER ];\n    SKP_int16   *LTP_res_ptr;\n    SKP_int     k, i, j;\n    SKP_int32   LTP_est;\n\n    x_ptr = x;\n    LTP_res_ptr = LTP_res;\n    for( k = 0; k < NB_SUBFR; k++ ) {\n\n        x_lag_ptr = x_ptr - pitchL[ k ];\n        for( i = 0; i < LTP_ORDER; i++ ) {\n            Btmp_Q14[ i ] = LTPCoef_Q14[ k * LTP_ORDER + i ];\n        }\n\n        /* LTP analysis FIR filter */\n        for( i = 0; i < subfr_length + pre_length; i++ ) {\n            LTP_res_ptr[ i ] = x_ptr[ i ];\n            \n            /* Long-term prediction */\n            LTP_est = SKP_SMULBB( x_lag_ptr[ LTP_ORDER / 2 ], Btmp_Q14[ 0 ] );\n            for( j = 1; j < LTP_ORDER; j++ ) {\n                LTP_est = SKP_SMLABB_ovflw( LTP_est, x_lag_ptr[ LTP_ORDER / 2 - j ], Btmp_Q14[ j ] );\n\t\t\t}\n            LTP_est = SKP_RSHIFT_ROUND( LTP_est, 14 ); // round and -> Q0\n\n            /* Subtract long-term prediction */\n            LTP_res_ptr[ i ] = ( SKP_int16 )SKP_SAT16( ( SKP_int32 )x_ptr[ i ] - LTP_est );\n\n            /* Scale residual */\n            LTP_res_ptr[ i ] = SKP_SMULWB( invGains_Q16[ k ], LTP_res_ptr[ i ] );\n\n            x_lag_ptr++;\n        }\n\n        /* Update pointers */\n        LTP_res_ptr += subfr_length + pre_length; \n        x_ptr       += subfr_length;\n    }\n}\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_LTP_scale_ctrl_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\n#define NB_THRESHOLDS           11\n\n/* Table containing trained thresholds for LTP scaling */\nstatic const SKP_int16 LTPScaleThresholds_Q15[ NB_THRESHOLDS ] = \n{\n    31129, 26214, 16384, 13107, 9830, 6554,\n     4915,  3276,  2621,  2458,    0\n};\n\nvoid SKP_Silk_LTP_scale_ctrl_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,     /* I/O  encoder state FIX                           */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl  /* I/O  encoder control FIX                         */\n)\n{\n    SKP_int round_loss, frames_per_packet;\n    SKP_int g_out_Q5, g_limit_Q15, thrld1_Q15, thrld2_Q15;\n\n    /* 1st order high-pass filter */\n    psEnc->HPLTPredCodGain_Q7 = SKP_max_int( psEncCtrl->LTPredCodGain_Q7 - psEnc->prevLTPredCodGain_Q7, 0 ) \n        + SKP_RSHIFT_ROUND( psEnc->HPLTPredCodGain_Q7, 1 );\n    \n    psEnc->prevLTPredCodGain_Q7 = psEncCtrl->LTPredCodGain_Q7;\n\n    /* combine input and filtered input */\n    g_out_Q5    = SKP_RSHIFT_ROUND( SKP_RSHIFT( psEncCtrl->LTPredCodGain_Q7, 1 ) + SKP_RSHIFT( psEnc->HPLTPredCodGain_Q7, 1 ), 3 );\n    g_limit_Q15 = SKP_Silk_sigm_Q15( g_out_Q5 - ( 3 << 5 ) );\n            \n    /* Default is minimum scaling */\n    psEncCtrl->sCmn.LTP_scaleIndex = 0;\n\n    /* Round the loss measure to whole pct */\n    round_loss = ( SKP_int )psEnc->sCmn.PacketLoss_perc;\n\n    /* Only scale if first frame in packet 0% */\n    if( psEnc->sCmn.nFramesInPayloadBuf == 0 ) {\n        \n        frames_per_packet = SKP_DIV32_16( psEnc->sCmn.PacketSize_ms, FRAME_LENGTH_MS );\n\n        round_loss += frames_per_packet - 1;\n        thrld1_Q15 = LTPScaleThresholds_Q15[ SKP_min_int( round_loss,     NB_THRESHOLDS - 1 ) ];\n        thrld2_Q15 = LTPScaleThresholds_Q15[ SKP_min_int( round_loss + 1, NB_THRESHOLDS - 1 ) ];\n    \n        if( g_limit_Q15 > thrld1_Q15 ) {\n            /* Maximum scaling */\n            psEncCtrl->sCmn.LTP_scaleIndex = 2;\n        } else if( g_limit_Q15 > thrld2_Q15 ) {\n            /* Medium scaling */\n            psEncCtrl->sCmn.LTP_scaleIndex = 1;\n        }\n    }\n    psEncCtrl->LTP_scale_Q14 = SKP_Silk_LTPScales_table_Q14[ psEncCtrl->sCmn.LTP_scaleIndex ];\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_MA.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_MA.c                                                      *\n *                                                                      *\n * Variable order MA filter                                             *\n *                                                                      *\n * Copyright 2006 (c), Skype Limited                                    *\n * Date: 060221                                                         *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n#if EMBEDDED_ARM<5\n/* Variable order MA prediction error filter */\nvoid SKP_Silk_MA_Prediction(\n    const SKP_int16      *in,            /* I:   Input signal                                */\n    const SKP_int16      *B,             /* I:   MA prediction coefficients, Q12 [order]     */\n    SKP_int32            *S,             /* I/O: State vector [order]                        */\n    SKP_int16            *out,           /* O:   Output signal                               */\n    const SKP_int32      len,            /* I:   Signal length                               */\n    const SKP_int32      order           /* I:   Filter order                                */\n)\n{\n    SKP_int   k, d, in16;\n    SKP_int32 out32;\n\n    for( k = 0; k < len; k++ ) {\n        in16 = in[ k ];\n        out32 = SKP_LSHIFT( in16, 12 ) - S[ 0 ];\n        out32 = SKP_RSHIFT_ROUND( out32, 12 );\n        \n        for( d = 0; d < order - 1; d++ ) {\n            S[ d ] = SKP_SMLABB_ovflw( S[ d + 1 ], in16, B[ d ] );\n        }\n        S[ order - 1 ] = SKP_SMULBB( in16, B[ order - 1 ] );\n\n        /* Limit */\n        out[ k ] = (SKP_int16)SKP_SAT16( out32 );\n    }\n}\n#endif\n\n#if EMBEDDED_ARM<5\n\nvoid SKP_Silk_LPC_analysis_filter(\n    const SKP_int16      *in,            /* I:   Input signal                                */\n    const SKP_int16      *B,             /* I:   MA prediction coefficients, Q12 [order]     */\n    SKP_int16            *S,             /* I/O: State vector [order]                        */\n    SKP_int16            *out,           /* O:   Output signal                               */\n    const SKP_int32      len,            /* I:   Signal length                               */\n    const SKP_int32      Order           /* I:   Filter order                                */\n)\n{\n    SKP_int   k, j, idx, Order_half = SKP_RSHIFT( Order, 1 );\n    SKP_int32 out32_Q12, out32;\n    SKP_int16 SA, SB;\n    /* Order must be even */\n    SKP_assert( 2 * Order_half == Order );\n\n    /* S[] values are in Q0 */\n    for( k = 0; k < len; k++ ) {\n        SA = S[ 0 ];\n        out32_Q12 = 0;\n        for( j = 0; j < ( Order_half - 1 ); j++ ) {\n            idx = SKP_SMULBB( 2, j ) + 1;\n            /* Multiply-add two prediction coefficients for each loop */\n            SB = S[ idx ];\n            S[ idx ] = SA;\n            out32_Q12 = SKP_SMLABB( out32_Q12, SA, B[ idx - 1 ] );\n            out32_Q12 = SKP_SMLABB( out32_Q12, SB, B[ idx ] );\n            SA = S[ idx + 1 ];\n            S[ idx + 1 ] = SB;\n        }\n\n        /* Unrolled loop: epilog */\n        SB = S[ Order - 1 ];\n        S[ Order - 1 ] = SA;\n        out32_Q12 = SKP_SMLABB( out32_Q12, SA, B[ Order - 2 ] );\n        out32_Q12 = SKP_SMLABB( out32_Q12, SB, B[ Order - 1 ] );\n\n        /* Subtract prediction */\n        out32_Q12 = SKP_SUB_SAT32( SKP_LSHIFT( (SKP_int32)in[ k ], 12 ), out32_Q12 );\n\n        /* Scale to Q0 */\n        out32 = SKP_RSHIFT_ROUND( out32_Q12, 12 );\n\n        /* Saturate output */\n        out[ k ] = ( SKP_int16 )SKP_SAT16( out32 );\n\n        /* Move input line */\n        S[ 0 ] = in[ k ];\n    }\n}\n#endif\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_NLSF2A.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/* conversion between prediction filter coefficients and LSFs   */\n/* order should be even                                         */\n/* a piecewise linear approximation maps LSF <-> cos(LSF)       */\n/* therefore the result is not accurate LSFs, but the two       */\n/* function are accurate inverses of each other                 */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* helper function for NLSF2A(..) */\nSKP_INLINE void SKP_Silk_NLSF2A_find_poly(\n    SKP_int32        *out,        /* o    intermediate polynomial, Q20            */\n    const SKP_int32    *cLSF,     /* i    vector of interleaved 2*cos(LSFs), Q20  */\n    SKP_int            dd         /* i    polynomial order (= 1/2 * filter order) */\n)\n{\n    SKP_int        k, n;\n    SKP_int32    ftmp;\n\n    out[0] = SKP_LSHIFT( 1, 20 );\n    out[1] = -cLSF[0];\n    for( k = 1; k < dd; k++ ) {\n        ftmp = cLSF[2*k];            // Q20\n        out[k+1] = SKP_LSHIFT( out[k-1], 1 ) - (SKP_int32)SKP_RSHIFT_ROUND64( SKP_SMULL( ftmp, out[k] ), 20 );\n        for( n = k; n > 1; n-- ) {\n            out[n] += out[n-2] - (SKP_int32)SKP_RSHIFT_ROUND64( SKP_SMULL( ftmp, out[n-1] ), 20 );\n        }\n        out[1] -= ftmp;\n    }\n}\n\n/* compute whitening filter coefficients from normalized line spectral frequencies */\nvoid SKP_Silk_NLSF2A(\n    SKP_int16       *a,               /* o    monic whitening filter coefficients in Q12,  [d]    */\n    const SKP_int    *NLSF,           /* i    normalized line spectral frequencies in Q15, [d]    */\n    const SKP_int    d                /* i    filter order (should be even)                       */\n)\n{\n    SKP_int k, i, dd;\n    SKP_int32 cos_LSF_Q20[SKP_Silk_MAX_ORDER_LPC];\n    SKP_int32 P[SKP_Silk_MAX_ORDER_LPC/2+1], Q[SKP_Silk_MAX_ORDER_LPC/2+1];\n    SKP_int32 Ptmp, Qtmp;\n    SKP_int32 f_int;\n    SKP_int32 f_frac;\n    SKP_int32 cos_val, delta;\n    SKP_int32 a_int32[SKP_Silk_MAX_ORDER_LPC];\n    SKP_int32 maxabs, absval, idx=0, sc_Q16; \n\n    SKP_assert(LSF_COS_TAB_SZ_FIX == 128);\n\n    /* convert LSFs to 2*cos(LSF(i)), using piecewise linear curve from table */\n    for( k = 0; k < d; k++ ) {\n        SKP_assert(NLSF[k] >= 0 );\n        SKP_assert(NLSF[k] <= 32767 );\n\n        /* f_int on a scale 0-127 (rounded down) */\n        f_int = SKP_RSHIFT( NLSF[k], 15 - 7 ); \n        \n        /* f_frac, range: 0..255 */\n        f_frac = NLSF[k] - SKP_LSHIFT( f_int, 15 - 7 ); \n\n        SKP_assert(f_int >= 0);\n        SKP_assert(f_int < LSF_COS_TAB_SZ_FIX );\n\n        /* Read start and end value from table */\n        cos_val = SKP_Silk_LSFCosTab_FIX_Q12[ f_int ];                /* Q12 */\n        delta   = SKP_Silk_LSFCosTab_FIX_Q12[ f_int + 1 ] - cos_val;  /* Q12, with a range of 0..200 */\n\n        /* Linear interpolation */\n        cos_LSF_Q20[k] = SKP_LSHIFT( cos_val, 8 ) + SKP_MUL( delta, f_frac ); /* Q20 */\n    }\n    \n    dd = SKP_RSHIFT( d, 1 );\n\n    /* generate even and odd polynomials using convolution */\n    SKP_Silk_NLSF2A_find_poly( P, &cos_LSF_Q20[0], dd );\n    SKP_Silk_NLSF2A_find_poly( Q, &cos_LSF_Q20[1], dd );\n\n    /* convert even and odd polynomials to SKP_int32 Q12 filter coefs */\n    for( k = 0; k < dd; k++ ) {\n        Ptmp = P[k+1] + P[k];\n        Qtmp = Q[k+1] - Q[k];\n\n        /* the Ptmp and Qtmp values at this stage need to fit in int32 */\n\n        a_int32[k]     = -SKP_RSHIFT_ROUND( Ptmp + Qtmp, 9 ); /* Q20 -> Q12 */\n        a_int32[d-k-1] =  SKP_RSHIFT_ROUND( Qtmp - Ptmp, 9 ); /* Q20 -> Q12 */\n    }\n\n    /* Limit the maximum absolute value of the prediction coefficients */\n    for( i = 0; i < 10; i++ ) {\n        /* Find maximum absolute value and its index */\n        maxabs = 0;\n        for( k = 0; k < d; k++ ) {\n            absval = SKP_abs( a_int32[k] );\n            if( absval > maxabs ) {\n                maxabs = absval;\n                idx       = k;\n            }    \n        }\n    \n        if( maxabs > SKP_int16_MAX ) {    \n            /* Reduce magnitude of prediction coefficients */\n            maxabs = SKP_min( maxabs, 98369 ); // ( SKP_int32_MAX / ( 65470 >> 2 ) ) + SKP_int16_MAX = 98369 \n            sc_Q16 = 65470 - SKP_DIV32( SKP_MUL( 65470 >> 2, maxabs - SKP_int16_MAX ), \n                                        SKP_RSHIFT32( SKP_MUL( maxabs, idx + 1), 2 ) );\n            SKP_Silk_bwexpander_32( a_int32, d, sc_Q16 );\n        } else {\n            break;\n        }\n    }    \n\n    /* Reached the last iteration */\n    if( i == 10 ) {\n        SKP_assert(0);\n        for( k = 0; k < d; k++ ) {\n            a_int32[k] = SKP_SAT16( a_int32[k] ); \n        }\n    }\n\n    /* Return as SKP_int16 Q12 coefficients */\n    for( k = 0; k < d; k++ ) {\n        a[k] = (SKP_int16)a_int32[k];\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_NLSF2A_stable.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n/* Convert NLSF parameters to stable AR prediction filter coefficients */\nvoid SKP_Silk_NLSF2A_stable(\n    SKP_int16                       pAR_Q12[ MAX_LPC_ORDER ],   /* O    Stabilized AR coefs [LPC_order]     */ \n    const SKP_int                   pNLSF[ MAX_LPC_ORDER ],     /* I    NLSF vector         [LPC_order]     */\n    const SKP_int                   LPC_order                   /* I    LPC/LSF order                       */\n)\n{\n    SKP_int   i;\n    SKP_int32 invGain_Q30;\n\n    SKP_Silk_NLSF2A( pAR_Q12, pNLSF, LPC_order );\n\n    /* Ensure stable LPCs */\n    for( i = 0; i < MAX_LPC_STABILIZE_ITERATIONS; i++ ) {\n        if( SKP_Silk_LPC_inverse_pred_gain( &invGain_Q30, pAR_Q12, LPC_order ) == 1 ) {\n            SKP_Silk_bwexpander( pAR_Q12, LPC_order, 65536 - SKP_SMULBB( 10 + i, i ) );\t\t/* 10_Q16 = 0.00015 */\n        } else {\n            break;\n        }\n    }\n\n    /* Reached the last iteration */\n    if( i == MAX_LPC_STABILIZE_ITERATIONS ) {\n        SKP_assert( 0 );\n        for( i = 0; i < LPC_order; i++ ) {\n            pAR_Q12[ i ] = 0;\n        }\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_NLSF_MSVQ_decode.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n/* NLSF vector decoder */\nvoid SKP_Silk_NLSF_MSVQ_decode(\n    SKP_int                         *pNLSF_Q15,     /* O    Pointer to decoded output vector [LPC_ORDER x 1]    */\n    const SKP_Silk_NLSF_CB_struct   *psNLSF_CB,     /* I    Pointer to NLSF codebook struct                     */\n    const SKP_int                   *NLSFIndices,   /* I    Pointer to NLSF indices          [nStages x 1]      */\n    const SKP_int                   LPC_order       /* I    LPC order used                                      */\n) \n{\n    const SKP_int16 *pCB_element;\n          SKP_int    s;\n          SKP_int    i;\n\n    /* Check that each index is within valid range */\n    SKP_assert( 0 <= NLSFIndices[ 0 ] && NLSFIndices[ 0 ] < psNLSF_CB->CBStages[ 0 ].nVectors );\n\n    /* Point to the first vector element */\n    pCB_element = &psNLSF_CB->CBStages[ 0 ].CB_NLSF_Q15[ SKP_MUL( NLSFIndices[ 0 ], LPC_order ) ];\n\n    /* Initialize with the codebook vector from stage 0 */\n    for( i = 0; i < LPC_order; i++ ) {\n        pNLSF_Q15[ i ] = ( SKP_int )pCB_element[ i ];\n    }\n          \n    for( s = 1; s < psNLSF_CB->nStages; s++ ) {\n        /* Check that each index is within valid range */\n        SKP_assert( 0 <= NLSFIndices[ s ] && NLSFIndices[ s ] < psNLSF_CB->CBStages[ s ].nVectors );\n\n        if( LPC_order == 16 ) {\n            /* Point to the first vector element */\n            pCB_element = &psNLSF_CB->CBStages[ s ].CB_NLSF_Q15[ SKP_LSHIFT( NLSFIndices[ s ], 4 ) ];\n\n            /* Add the codebook vector from the current stage */\n            pNLSF_Q15[  0 ] += pCB_element[  0 ];\n            pNLSF_Q15[  1 ] += pCB_element[  1 ];\n            pNLSF_Q15[  2 ] += pCB_element[  2 ];\n            pNLSF_Q15[  3 ] += pCB_element[  3 ];\n            pNLSF_Q15[  4 ] += pCB_element[  4 ];\n            pNLSF_Q15[  5 ] += pCB_element[  5 ];\n            pNLSF_Q15[  6 ] += pCB_element[  6 ];\n            pNLSF_Q15[  7 ] += pCB_element[  7 ];\n            pNLSF_Q15[  8 ] += pCB_element[  8 ];\n            pNLSF_Q15[  9 ] += pCB_element[  9 ];\n            pNLSF_Q15[ 10 ] += pCB_element[ 10 ];\n            pNLSF_Q15[ 11 ] += pCB_element[ 11 ];\n            pNLSF_Q15[ 12 ] += pCB_element[ 12 ];\n            pNLSF_Q15[ 13 ] += pCB_element[ 13 ];\n            pNLSF_Q15[ 14 ] += pCB_element[ 14 ];\n            pNLSF_Q15[ 15 ] += pCB_element[ 15 ];\n        } else {\n            /* Point to the first vector element */\n            pCB_element = &psNLSF_CB->CBStages[ s ].CB_NLSF_Q15[ SKP_SMULBB( NLSFIndices[ s ], LPC_order ) ];\n\n            /* Add the codebook vector from the current stage */\n            for( i = 0; i < LPC_order; i++ ) {\n                pNLSF_Q15[ i ] += pCB_element[ i ];\n            }\n        }\n    }\n\n    /* NLSF stabilization */\n    SKP_Silk_NLSF_stabilize( pNLSF_Q15, psNLSF_CB->NDeltaMin_Q15, LPC_order );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_NLSF_MSVQ_encode_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\n/***********************/\n/* NLSF vector encoder */\n/***********************/\nvoid SKP_Silk_NLSF_MSVQ_encode_FIX(\n          SKP_int                   *NLSFIndices,           /* O    Codebook path vector [ CB_STAGES ]      */\n          SKP_int                   *pNLSF_Q15,             /* I/O  Quantized NLSF vector [ LPC_ORDER ]     */\n    const SKP_Silk_NLSF_CB_struct   *psNLSF_CB,             /* I    Codebook object                         */\n    const SKP_int                   *pNLSF_q_Q15_prev,      /* I    Prev. quantized NLSF vector [LPC_ORDER] */\n    const SKP_int                   *pW_Q6,                 /* I    NLSF weight vector [ LPC_ORDER ]        */\n    const SKP_int                   NLSF_mu_Q15,            /* I    Rate weight for the RD optimization     */\n    const SKP_int                   NLSF_mu_fluc_red_Q16,   /* I    Fluctuation reduction error weight      */\n    const SKP_int                   NLSF_MSVQ_Survivors,    /* I    Max survivors from each stage           */\n    const SKP_int                   LPC_order,              /* I    LPC order                               */\n    const SKP_int                   deactivate_fluc_red     /* I    Deactivate fluctuation reduction        */\n)\n{\n    SKP_int     i, s, k, cur_survivors = 0, prev_survivors, min_survivors, input_index, cb_index, bestIndex;\n    SKP_int32   rateDistThreshold_Q18;\n#if( NLSF_MSVQ_FLUCTUATION_REDUCTION == 1 )\n    SKP_int32   se_Q15, wsse_Q20, bestRateDist_Q20;\n#endif\n\n#if( LOW_COMPLEXITY_ONLY == 1 )\n    SKP_int32   pRateDist_Q18[  NLSF_MSVQ_TREE_SEARCH_MAX_VECTORS_EVALUATED_LC_MODE ];\n    SKP_int32   pRate_Q5[       MAX_NLSF_MSVQ_SURVIVORS_LC_MODE ];\n    SKP_int32   pRate_new_Q5[   MAX_NLSF_MSVQ_SURVIVORS_LC_MODE ];\n    SKP_int     pTempIndices[   MAX_NLSF_MSVQ_SURVIVORS_LC_MODE ];\n    SKP_int     pPath[          MAX_NLSF_MSVQ_SURVIVORS_LC_MODE * NLSF_MSVQ_MAX_CB_STAGES ];\n    SKP_int     pPath_new[      MAX_NLSF_MSVQ_SURVIVORS_LC_MODE * NLSF_MSVQ_MAX_CB_STAGES ];\n    SKP_int     pRes_Q15[       MAX_NLSF_MSVQ_SURVIVORS_LC_MODE * MAX_LPC_ORDER ];\n    SKP_int     pRes_new_Q15[   MAX_NLSF_MSVQ_SURVIVORS_LC_MODE * MAX_LPC_ORDER ];\n#else\n    SKP_int32   pRateDist_Q18[  NLSF_MSVQ_TREE_SEARCH_MAX_VECTORS_EVALUATED ];\n    SKP_int32   pRate_Q5[       MAX_NLSF_MSVQ_SURVIVORS ];\n    SKP_int32   pRate_new_Q5[   MAX_NLSF_MSVQ_SURVIVORS ];\n    SKP_int     pTempIndices[   MAX_NLSF_MSVQ_SURVIVORS ];\n    SKP_int     pPath[          MAX_NLSF_MSVQ_SURVIVORS * NLSF_MSVQ_MAX_CB_STAGES ];\n    SKP_int     pPath_new[      MAX_NLSF_MSVQ_SURVIVORS * NLSF_MSVQ_MAX_CB_STAGES ];\n    SKP_int     pRes_Q15[       MAX_NLSF_MSVQ_SURVIVORS * MAX_LPC_ORDER ];\n    SKP_int     pRes_new_Q15[   MAX_NLSF_MSVQ_SURVIVORS * MAX_LPC_ORDER ];\n#endif\n\n    const SKP_int   *pConstInt;\n          SKP_int   *pInt;\n    const SKP_int16 *pCB_element;\n    const SKP_Silk_NLSF_CBS *pCurrentCBStage;\n\n#ifdef USE_UNQUANTIZED_LSFS\n    SKP_int NLSF_orig[ MAX_LPC_ORDER ];\n    SKP_memcpy( NLSF_orig, pNLSF_Q15, LPC_order * sizeof( SKP_int ) );\n#endif\n\n    SKP_assert( NLSF_MSVQ_Survivors <= MAX_NLSF_MSVQ_SURVIVORS );\n    SKP_assert( ( LOW_COMPLEXITY_ONLY == 0 ) || ( NLSF_MSVQ_Survivors <= MAX_NLSF_MSVQ_SURVIVORS_LC_MODE ) );\n\n\n    /****************************************************/\n    /* Tree search for the multi-stage vector quantizer */\n    /****************************************************/\n\n    /* Clear accumulated rates */\n    SKP_memset( pRate_Q5, 0, NLSF_MSVQ_Survivors * sizeof( SKP_int32 ) );\n    \n    /* Copy NLSFs into residual signal vector */\n    for( i = 0; i < LPC_order; i++ ) {\n        pRes_Q15[ i ] = pNLSF_Q15[ i ];\n    }\n\n    /* Set first stage values */\n    prev_survivors = 1;\n\n    /* Minimum number of survivors */\n    min_survivors = NLSF_MSVQ_Survivors / 2;\n\n    /* Loop over all stages */\n    for( s = 0; s < psNLSF_CB->nStages; s++ ) {\n\n        /* Set a pointer to the current stage codebook */\n        pCurrentCBStage = &psNLSF_CB->CBStages[ s ];\n\n        /* Calculate the number of survivors in the current stage */\n        cur_survivors = SKP_min_32( NLSF_MSVQ_Survivors, SKP_SMULBB( prev_survivors, pCurrentCBStage->nVectors ) );\n\n#if( NLSF_MSVQ_FLUCTUATION_REDUCTION == 0 )\n        /* Find a single best survivor in the last stage, if we */\n        /* do not need candidates for fluctuation reduction     */\n        if( s == psNLSF_CB->nStages - 1 ) {\n            cur_survivors = 1;\n        }\n#endif\n\n        /* Nearest neighbor clustering for multiple input data vectors */\n        SKP_Silk_NLSF_VQ_rate_distortion_FIX( pRateDist_Q18, pCurrentCBStage, pRes_Q15, pW_Q6, \n            pRate_Q5, NLSF_mu_Q15, prev_survivors, LPC_order );\n\n        /* Sort the rate-distortion errors */\n        SKP_Silk_insertion_sort_increasing( pRateDist_Q18, pTempIndices, \n            prev_survivors * pCurrentCBStage->nVectors, cur_survivors );\n\n        /* Discard survivors with rate-distortion values too far above the best one */\n        if( pRateDist_Q18[ 0 ] < SKP_int32_MAX / MAX_NLSF_MSVQ_SURVIVORS ) {\n            rateDistThreshold_Q18 = SKP_SMLAWB( pRateDist_Q18[ 0 ], \n                SKP_MUL( NLSF_MSVQ_Survivors, pRateDist_Q18[ 0 ] ), SKP_FIX_CONST( NLSF_MSVQ_SURV_MAX_REL_RD, 16 ) );\n            while( pRateDist_Q18[ cur_survivors - 1 ] > rateDistThreshold_Q18 && cur_survivors > min_survivors ) {\n                cur_survivors--;\n            }\n        }\n        /* Update accumulated codebook contributions for the 'cur_survivors' best codebook indices */\n        for( k = 0; k < cur_survivors; k++ ) { \n            if( s > 0 ) {\n                /* Find the indices of the input and the codebook vector */\n                if( pCurrentCBStage->nVectors == 8 ) {\n                    input_index = SKP_RSHIFT( pTempIndices[ k ], 3 );\n                    cb_index    = pTempIndices[ k ] & 7;\n                } else {\n                    input_index = SKP_DIV32_16( pTempIndices[ k ], pCurrentCBStage->nVectors );  \n                    cb_index    = pTempIndices[ k ] - SKP_SMULBB( input_index, pCurrentCBStage->nVectors );\n                }\n            } else {\n                /* Find the indices of the input and the codebook vector */\n                input_index = 0;\n                cb_index    = pTempIndices[ k ];\n            }\n\n            /* Subtract new contribution from the previous residual vector for each of 'cur_survivors' */\n            pConstInt   = &pRes_Q15[ SKP_SMULBB( input_index, LPC_order ) ];\n            pCB_element = &pCurrentCBStage->CB_NLSF_Q15[ SKP_SMULBB( cb_index, LPC_order ) ];\n            pInt        = &pRes_new_Q15[ SKP_SMULBB( k, LPC_order ) ];\n            for( i = 0; i < LPC_order; i++ ) {\n                pInt[ i ] = pConstInt[ i ] - ( SKP_int )pCB_element[ i ];\n            }\n\n            /* Update accumulated rate for stage 1 to the current */\n            pRate_new_Q5[ k ] = pRate_Q5[ input_index ] + pCurrentCBStage->Rates_Q5[ cb_index ];\n\n            /* Copy paths from previous matrix, starting with the best path */\n            pConstInt = &pPath[ SKP_SMULBB( input_index, psNLSF_CB->nStages ) ];\n            pInt      = &pPath_new[ SKP_SMULBB( k, psNLSF_CB->nStages ) ];\n            for( i = 0; i < s; i++ ) {\n                pInt[ i ] = pConstInt[ i ];\n            }\n            /* Write the current stage indices for the 'cur_survivors' to the best path matrix */\n            pInt[ s ] = cb_index;\n        }\n\n        if( s < psNLSF_CB->nStages - 1 ) {\n            /* Copy NLSF residual matrix for next stage */\n            SKP_memcpy( pRes_Q15, pRes_new_Q15, SKP_SMULBB( cur_survivors, LPC_order ) * sizeof( SKP_int ) );\n\n            /* Copy rate vector for next stage */\n            SKP_memcpy( pRate_Q5, pRate_new_Q5, cur_survivors * sizeof( SKP_int32 ) );\n\n            /* Copy best path matrix for next stage */\n            SKP_memcpy( pPath, pPath_new, SKP_SMULBB( cur_survivors, psNLSF_CB->nStages ) * sizeof( SKP_int ) );\n        }\n\n        prev_survivors = cur_survivors;\n    }\n\n    /* (Preliminary) index of the best survivor, later to be decoded */\n    bestIndex = 0;\n\n#if( NLSF_MSVQ_FLUCTUATION_REDUCTION == 1 )\n    /******************************/\n    /* NLSF fluctuation reduction */\n    /******************************/\n    if( deactivate_fluc_red != 1 ) {\n    \n        /* Search among all survivors, now taking also weighted fluctuation errors into account */\n        bestRateDist_Q20 = SKP_int32_MAX;\n        for( s = 0; s < cur_survivors; s++ ) {\n            /* Decode survivor to compare with previous quantized NLSF vector */\n            SKP_Silk_NLSF_MSVQ_decode( pNLSF_Q15, psNLSF_CB, &pPath_new[ SKP_SMULBB( s, psNLSF_CB->nStages ) ], LPC_order );\n\n            /* Compare decoded NLSF vector with the previously quantized vector */ \n            wsse_Q20 = 0;\n            for( i = 0; i < LPC_order; i += 2 ) {\n                /* Compute weighted squared quantization error for index i */\n                se_Q15 = pNLSF_Q15[ i ] - pNLSF_q_Q15_prev[ i ]; // range: [ -32767 : 32767 ]\n                wsse_Q20 = SKP_SMLAWB( wsse_Q20, SKP_SMULBB( se_Q15, se_Q15 ), pW_Q6[ i ] );\n\n                /* Compute weighted squared quantization error for index i + 1 */\n                se_Q15 = pNLSF_Q15[ i + 1 ] - pNLSF_q_Q15_prev[ i + 1 ]; // range: [ -32767 : 32767 ]\n                wsse_Q20 = SKP_SMLAWB( wsse_Q20, SKP_SMULBB( se_Q15, se_Q15 ), pW_Q6[ i + 1 ] );\n            }\n            SKP_assert( wsse_Q20 >= 0 );\n\n            /* Add the fluctuation reduction penalty to the rate distortion error */\n            wsse_Q20 = SKP_ADD_POS_SAT32( pRateDist_Q18[ s ], SKP_SMULWB( wsse_Q20, NLSF_mu_fluc_red_Q16 ) );\n\n            /* Keep index of best survivor */\n            if( wsse_Q20 < bestRateDist_Q20 ) {\n                bestRateDist_Q20 = wsse_Q20;\n                bestIndex = s;\n            }\n        }\n    }\n#endif\n\n    /* Copy best path to output argument */\n    SKP_memcpy( NLSFIndices, &pPath_new[ SKP_SMULBB( bestIndex, psNLSF_CB->nStages ) ], psNLSF_CB->nStages * sizeof( SKP_int ) );\n\n    /* Decode and stabilize the best survivor */\n    SKP_Silk_NLSF_MSVQ_decode( pNLSF_Q15, psNLSF_CB, NLSFIndices, LPC_order );\n\n#ifdef USE_UNQUANTIZED_LSFS\n    SKP_memcpy( pNLSF_Q15, NLSF_orig, LPC_order * sizeof( SKP_int ) );\n#endif\n\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_NLSF_VQ_rate_distortion_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\n/* Rate-Distortion calculations for multiple input data vectors */\nvoid SKP_Silk_NLSF_VQ_rate_distortion_FIX(\n    SKP_int32                       *pRD_Q20,           /* O    Rate-distortion values [psNLSF_CBS->nVectors*N] */\n    const SKP_Silk_NLSF_CBS         *psNLSF_CBS,        /* I    NLSF codebook stage struct                      */\n    const SKP_int                   *in_Q15,            /* I    Input vectors to be quantized                   */\n    const SKP_int                   *w_Q6,              /* I    Weight vector                                   */\n    const SKP_int32                 *rate_acc_Q5,       /* I    Accumulated rates from previous stage           */\n    const SKP_int                   mu_Q15,             /* I    Weight between weighted error and rate          */\n    const SKP_int                   N,                  /* I    Number of input vectors to be quantized         */\n    const SKP_int                   LPC_order           /* I    LPC order                                       */\n)\n{\n    SKP_int   i, n;\n    SKP_int32 *pRD_vec_Q20;\n\n    /* Compute weighted quantization errors for all input vectors over one codebook stage */\n    SKP_Silk_NLSF_VQ_sum_error_FIX( pRD_Q20, in_Q15, w_Q6, psNLSF_CBS->CB_NLSF_Q15, \n        N, psNLSF_CBS->nVectors, LPC_order );\n\n    /* Loop over input vectors */\n    pRD_vec_Q20 = pRD_Q20;\n    for( n = 0; n < N; n++ ) {\n        /* Add rate cost to error for each codebook vector */\n        for( i = 0; i < psNLSF_CBS->nVectors; i++ ) {\n            SKP_assert( rate_acc_Q5[ n ] + psNLSF_CBS->Rates_Q5[ i ] >= 0 );\n            SKP_assert( rate_acc_Q5[ n ] + psNLSF_CBS->Rates_Q5[ i ] <= SKP_int16_MAX );\n            pRD_vec_Q20[ i ] = SKP_SMLABB( pRD_vec_Q20[ i ], rate_acc_Q5[ n ] + psNLSF_CBS->Rates_Q5[ i ], mu_Q15 );\n            SKP_assert( pRD_vec_Q20[ i ] >= 0 );\n        }\n        pRD_vec_Q20 += psNLSF_CBS->nVectors;\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_NLSF_VQ_sum_error_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\n#if (!defined(__mips__)) && (EMBEDDED_ARM < 6)\n\n/* Compute weighted quantization errors for an LPC_order element input vector, over one codebook stage */\nvoid SKP_Silk_NLSF_VQ_sum_error_FIX(\n    SKP_int32                       *err_Q20,           /* O    Weighted quantization errors  [N*K]         */\n    const SKP_int                   *in_Q15,            /* I    Input vectors to be quantized [N*LPC_order] */\n    const SKP_int                   *w_Q6,              /* I    Weighting vectors             [N*LPC_order] */\n    const SKP_int16                 *pCB_Q15,           /* I    Codebook vectors              [K*LPC_order] */\n    const SKP_int                   N,                  /* I    Number of input vectors                     */\n    const SKP_int                   K,                  /* I    Number of codebook vectors                  */\n    const SKP_int                   LPC_order           /* I    Number of LPCs                              */\n)\n{\n    SKP_int         i, n, m;\n    SKP_int32       diff_Q15, sum_error, Wtmp_Q6;\n    SKP_int32       Wcpy_Q6[ MAX_LPC_ORDER / 2 ];\n    const SKP_int16 *cb_vec_Q15;\n\n    SKP_assert( LPC_order <= 16 );\n    SKP_assert( ( LPC_order & 1 ) == 0 );\n\n    /* Copy to local stack and pack two weights per int32 */\n    for( m = 0; m < SKP_RSHIFT( LPC_order, 1 ); m++ ) {\n        Wcpy_Q6[ m ] = w_Q6[ 2 * m ] | SKP_LSHIFT( ( SKP_int32 )w_Q6[ 2 * m + 1 ], 16 );\n    }\n\n    /* Loop over input vectors */\n    for( n = 0; n < N; n++ ) {\n        /* Loop over codebook */\n        cb_vec_Q15 = pCB_Q15;\n        for( i = 0; i < K; i++ ) {\n            sum_error = 0;\n            for( m = 0; m < LPC_order; m += 2 ) {\n                /* Get two weights packed in an int32 */\n                Wtmp_Q6 = Wcpy_Q6[ SKP_RSHIFT( m, 1 ) ];\n\n                /* Compute weighted squared quantization error for index m */\n                diff_Q15 = in_Q15[ m ] - *cb_vec_Q15++; // range: [ -32767 : 32767 ]\n                sum_error = SKP_SMLAWB( sum_error, SKP_SMULBB( diff_Q15, diff_Q15 ), Wtmp_Q6 );\n\n                /* Compute weighted squared quantization error for index m + 1 */\n                diff_Q15 = in_Q15[m + 1] - *cb_vec_Q15++; // range: [ -32767 : 32767 ]\n                sum_error = SKP_SMLAWT( sum_error, SKP_SMULBB( diff_Q15, diff_Q15 ), Wtmp_Q6 );\n            }\n            SKP_assert( sum_error >= 0 );\n            err_Q20[ i ] = sum_error;\n        }\n        err_Q20 += K;\n        in_Q15 += LPC_order;\n    }\n}\n\n#endif\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_NLSF_VQ_weights_laroia.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* \nR. Laroia, N. Phamdo and N. Farvardin, \"Robust and Efficient Quantization of Speech LSP\nParameters Using Structured Vector Quantization\", Proc. IEEE Int. Conf. Acoust., Speech,\nSignal Processing, pp. 641-644, 1991.\n*/\n\n#define Q_OUT                       6\n#define MIN_NDELTA                  3\n\n/* Laroia low complexity NLSF weights */\nvoid SKP_Silk_NLSF_VQ_weights_laroia(\n    SKP_int             *pNLSFW_Q6,         /* O: Pointer to input vector weights           [D x 1]     */\n    const SKP_int       *pNLSF_Q15,         /* I: Pointer to input vector                   [D x 1]     */ \n    const SKP_int       D                   /* I: Input vector dimension (even)                         */\n)\n{\n    SKP_int   k;\n    SKP_int32 tmp1_int, tmp2_int;\n    \n    /* Check that we are guaranteed to end up within the required range */\n    SKP_assert( D > 0 );\n    SKP_assert( ( D & 1 ) == 0 );\n    \n    /* First value */\n    tmp1_int = SKP_max_int( pNLSF_Q15[ 0 ], MIN_NDELTA );\n    tmp1_int = SKP_DIV32_16( 1 << ( 15 + Q_OUT ), tmp1_int );\n    tmp2_int = SKP_max_int( pNLSF_Q15[ 1 ] - pNLSF_Q15[ 0 ], MIN_NDELTA );\n    tmp2_int = SKP_DIV32_16( 1 << ( 15 + Q_OUT ), tmp2_int );\n    pNLSFW_Q6[ 0 ] = (SKP_int)SKP_min_int( tmp1_int + tmp2_int, SKP_int16_MAX );\n    SKP_assert( pNLSFW_Q6[ 0 ] > 0 );\n    \n    /* Main loop */\n    for( k = 1; k < D - 1; k += 2 ) {\n        tmp1_int = SKP_max_int( pNLSF_Q15[ k + 1 ] - pNLSF_Q15[ k ], MIN_NDELTA );\n        tmp1_int = SKP_DIV32_16( 1 << ( 15 + Q_OUT ), tmp1_int );\n        pNLSFW_Q6[ k ] = (SKP_int)SKP_min_int( tmp1_int + tmp2_int, SKP_int16_MAX );\n        SKP_assert( pNLSFW_Q6[ k ] > 0 );\n\n        tmp2_int = SKP_max_int( pNLSF_Q15[ k + 2 ] - pNLSF_Q15[ k + 1 ], MIN_NDELTA );\n        tmp2_int = SKP_DIV32_16( 1 << ( 15 + Q_OUT ), tmp2_int );\n        pNLSFW_Q6[ k + 1 ] = (SKP_int)SKP_min_int( tmp1_int + tmp2_int, SKP_int16_MAX );\n        SKP_assert( pNLSFW_Q6[ k + 1 ] > 0 );\n    }\n    \n    /* Last value */\n    tmp1_int = SKP_max_int( ( 1 << 15 ) - pNLSF_Q15[ D - 1 ], MIN_NDELTA );\n    tmp1_int = SKP_DIV32_16( 1 << ( 15 + Q_OUT ), tmp1_int );\n    pNLSFW_Q6[ D - 1 ] = (SKP_int)SKP_min_int( tmp1_int + tmp2_int, SKP_int16_MAX );\n    SKP_assert( pNLSFW_Q6[ D - 1 ] > 0 );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_NLSF_stabilize.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/* NLSF stabilizer:                                         */\n/*                                                          */\n/* - Moves NLSFs futher apart if they are too close         */\n/* - Moves NLSFs away from borders if they are too close    */\n/* - High effort to achieve a modification with minimum     */\n/*     Euclidean distance to input vector                   */\n/* - Output are sorted NLSF coefficients                    */\n/*                                                          */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Constant Definitions */\n#define MAX_LOOPS        20\n\n/* NLSF stabilizer, for a single input data vector */\nvoid SKP_Silk_NLSF_stabilize(\n          SKP_int    *NLSF_Q15,            /* I/O:  Unstable/stabilized normalized LSF vector in Q15 [L]                    */\n    const SKP_int    *NDeltaMin_Q15,       /* I:    Normalized delta min vector in Q15, NDeltaMin_Q15[L] must be >= 1 [L+1] */\n    const SKP_int     L                    /* I:    Number of NLSF parameters in the input vector                           */\n)\n{\n    SKP_int        center_freq_Q15, diff_Q15, min_center_Q15, max_center_Q15;\n    SKP_int32    min_diff_Q15;\n    SKP_int        loops;\n    SKP_int        i, I=0, k;\n\n    /* This is necessary to ensure an output within range of a SKP_int16 */\n    SKP_assert( NDeltaMin_Q15[L] >= 1 );\n\n    for( loops = 0; loops < MAX_LOOPS; loops++ ) {\n        /**************************/\n        /* Find smallest distance */\n        /**************************/\n        /* First element */\n        min_diff_Q15 = NLSF_Q15[0] - NDeltaMin_Q15[0];\n        I = 0;\n        /* Middle elements */\n        for( i = 1; i <= L-1; i++ ) {\n            diff_Q15 = NLSF_Q15[i] - ( NLSF_Q15[i-1] + NDeltaMin_Q15[i] );\n            if( diff_Q15 < min_diff_Q15 ) {\n                min_diff_Q15 = diff_Q15;\n                I = i;\n            }\n        }\n        /* Last element */\n        diff_Q15 = (1<<15) - ( NLSF_Q15[L-1] + NDeltaMin_Q15[L] );\n        if( diff_Q15 < min_diff_Q15 ) {\n            min_diff_Q15 = diff_Q15;\n            I = L;\n        }\n\n        /***************************************************/\n        /* Now check if the smallest distance non-negative */\n        /***************************************************/\n        if (min_diff_Q15 >= 0) {\n            return;\n        }\n\n        if( I == 0 ) {\n            /* Move away from lower limit */\n            NLSF_Q15[0] = NDeltaMin_Q15[0];\n        \n        } else if( I == L) {\n            /* Move away from higher limit */\n            NLSF_Q15[L-1] = (1<<15) - NDeltaMin_Q15[L];\n        \n        } else {\n            /* Find the lower extreme for the location of the current center frequency */ \n            min_center_Q15 = 0;\n            for( k = 0; k < I; k++ ) {\n                min_center_Q15 += NDeltaMin_Q15[k];\n            }\n            min_center_Q15 += SKP_RSHIFT( NDeltaMin_Q15[I], 1 );\n\n            /* Find the upper extreme for the location of the current center frequency */\n            max_center_Q15 = (1<<15);\n            for( k = L; k > I; k-- ) {\n                max_center_Q15 -= NDeltaMin_Q15[k];\n            }\n            max_center_Q15 -= ( NDeltaMin_Q15[I] - SKP_RSHIFT( NDeltaMin_Q15[I], 1 ) );\n\n            /* Move apart, sorted by value, keeping the same center frequency */\n            center_freq_Q15 = SKP_LIMIT_32( SKP_RSHIFT_ROUND( (SKP_int32)NLSF_Q15[I-1] + (SKP_int32)NLSF_Q15[I], 1 ),\n                min_center_Q15, max_center_Q15 );\n            NLSF_Q15[I-1] = center_freq_Q15 - SKP_RSHIFT( NDeltaMin_Q15[I], 1 );\n            NLSF_Q15[I] = NLSF_Q15[I-1] + NDeltaMin_Q15[I];\n        }\n    }\n\n    /* Safe and simple fall back method, which is less ideal than the above */\n    if( loops == MAX_LOOPS )\n    {\n        /* Insertion sort (fast for already almost sorted arrays):   */\n        /* Best case:  O(n)   for an already sorted array            */\n        /* Worst case: O(n^2) for an inversely sorted array          */\n        SKP_Silk_insertion_sort_increasing_all_values(&NLSF_Q15[0], L);\n            \n        /* First NLSF should be no less than NDeltaMin[0] */\n        NLSF_Q15[0] = SKP_max_int( NLSF_Q15[0], NDeltaMin_Q15[0] );\n        \n        /* Keep delta_min distance between the NLSFs */\n        for( i = 1; i < L; i++ )\n            NLSF_Q15[i] = SKP_max_int( NLSF_Q15[i], NLSF_Q15[i-1] + NDeltaMin_Q15[i] );\n\n        /* Last NLSF should be no higher than 1 - NDeltaMin[L] */\n        NLSF_Q15[L-1] = SKP_min_int( NLSF_Q15[L-1], (1<<15) - NDeltaMin_Q15[L] );\n\n        /* Keep NDeltaMin distance between the NLSFs */\n        for( i = L-2; i >= 0; i-- ) \n            NLSF_Q15[i] = SKP_min_int( NLSF_Q15[i], NLSF_Q15[i+1] - NDeltaMin_Q15[i+1] );\n    }\n}\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_NSQ.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\nSKP_INLINE void SKP_Silk_nsq_scale_states(\n    SKP_Silk_nsq_state  *NSQ,               /* I/O NSQ state                        */\n    const SKP_int16     x[],                /* I input in Q0                        */\n    SKP_int32           x_sc_Q10[],         /* O input scaled with 1/Gain           */\n    SKP_int             subfr_length,       /* I length of input                    */\n    const SKP_int16     sLTP[],             /* I re-whitened LTP state in Q0        */\n    SKP_int32           sLTP_Q16[],         /* O LTP state matching scaled input    */\n    SKP_int             subfr,              /* I subframe number                    */\n    const SKP_int       LTP_scale_Q14,      /* I                                    */\n    const SKP_int32     Gains_Q16[ NB_SUBFR ], /* I                                 */\n    const SKP_int       pitchL[ NB_SUBFR ]  /* I                                    */\n);\n\nSKP_INLINE void SKP_Silk_noise_shape_quantizer(\n    SKP_Silk_nsq_state  *NSQ,               /* I/O  NSQ state                       */\n    SKP_int             sigtype,            /* I    Signal type                     */\n    const SKP_int32     x_sc_Q10[],         /* I                                    */\n    SKP_int8            q[],                /* O                                    */\n    SKP_int16           xq[],               /* O                                    */\n    SKP_int32           sLTP_Q16[],         /* I/O  LTP state                       */\n    const SKP_int16     a_Q12[],            /* I    Short term prediction coefs     */\n    const SKP_int16     b_Q14[],            /* I    Long term prediction coefs      */\n    const SKP_int16     AR_shp_Q13[],       /* I    Noise shaping AR coefs          */\n    SKP_int             lag,                /* I    Pitch lag                       */\n    SKP_int32           HarmShapeFIRPacked_Q14, /* I                                */\n    SKP_int             Tilt_Q14,           /* I    Spectral tilt                   */\n    SKP_int32           LF_shp_Q14,         /* I                                    */\n    SKP_int32           Gain_Q16,           /* I                                    */\n    SKP_int             Lambda_Q10,         /* I                                    */\n    SKP_int             offset_Q10,         /* I                                    */\n    SKP_int             length,             /* I    Input length                    */\n    SKP_int             shapingLPCOrder,    /* I    Noise shaping AR filter order   */\n    SKP_int             predictLPCOrder     /* I    Prediction filter order         */\n);\n\nvoid SKP_Silk_NSQ(\n    SKP_Silk_encoder_state          *psEncC,                                    /* I/O  Encoder State                       */\n    SKP_Silk_encoder_control        *psEncCtrlC,                                /* I    Encoder Control                     */\n    SKP_Silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                           */\n    const SKP_int16                 x[],                                        /* I    prefiltered input signal            */\n    SKP_int8                        q[],                                        /* O    quantized qulse signal              */\n    const SKP_int                   LSFInterpFactor_Q2,                         /* I    LSF interpolation factor in Q2      */\n    const SKP_int16                 PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefficients  */\n    const SKP_int16                 LTPCoef_Q14[ LTP_ORDER * NB_SUBFR ],        /* I    Long term prediction coefficients   */\n    const SKP_int16                 AR2_Q13[ NB_SUBFR * MAX_SHAPE_LPC_ORDER ],  /* I                                        */\n    const SKP_int                   HarmShapeGain_Q14[ NB_SUBFR ],              /* I                                        */\n    const SKP_int                   Tilt_Q14[ NB_SUBFR ],                       /* I    Spectral tilt                       */\n    const SKP_int32                 LF_shp_Q14[ NB_SUBFR ],                     /* I                                        */\n    const SKP_int32                 Gains_Q16[ NB_SUBFR ],                      /* I                                        */\n    const SKP_int                   Lambda_Q10,                                 /* I                                        */\n    const SKP_int                   LTP_scale_Q14                               /* I    LTP state scaling                   */\n)\n{\n    SKP_int     k, lag, start_idx, LSF_interpolation_flag;\n    const SKP_int16 *A_Q12, *B_Q14, *AR_shp_Q13;\n    SKP_int16   *pxq;\n    SKP_int32   sLTP_Q16[ 2 * MAX_FRAME_LENGTH ];\n    SKP_int16   sLTP[     2 * MAX_FRAME_LENGTH ];\n    SKP_int32   HarmShapeFIRPacked_Q14;\n    SKP_int     offset_Q10;\n    SKP_int32   FiltState[ MAX_LPC_ORDER ];\n    SKP_int32   x_sc_Q10[ MAX_FRAME_LENGTH / NB_SUBFR ];\n\n    NSQ->rand_seed  =  psEncCtrlC->Seed;\n    /* Set unvoiced lag to the previous one, overwrite later for voiced */\n    lag             = NSQ->lagPrev;\n\n    SKP_assert( NSQ->prev_inv_gain_Q16 != 0 );\n\n    offset_Q10 = SKP_Silk_Quantization_Offsets_Q10[ psEncCtrlC->sigtype ][ psEncCtrlC->QuantOffsetType ];\n\n    if( LSFInterpFactor_Q2 == ( 1 << 2 ) ) {\n        LSF_interpolation_flag = 0;\n    } else {\n        LSF_interpolation_flag = 1;\n    }\n\n    /* Setup pointers to start of sub frame */\n    NSQ->sLTP_shp_buf_idx = psEncC->frame_length;\n    NSQ->sLTP_buf_idx     = psEncC->frame_length;\n    pxq                   = &NSQ->xq[ psEncC->frame_length ];\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        A_Q12      = &PredCoef_Q12[ (( k >> 1 ) | ( 1 - LSF_interpolation_flag )) * MAX_LPC_ORDER ];\n        B_Q14      = &LTPCoef_Q14[ k * LTP_ORDER ];\n        AR_shp_Q13 = &AR2_Q13[     k * MAX_SHAPE_LPC_ORDER ];\n\n        /* Noise shape parameters */\n        SKP_assert( HarmShapeGain_Q14[ k ] >= 0 );\n        HarmShapeFIRPacked_Q14  =                          SKP_RSHIFT( HarmShapeGain_Q14[ k ], 2 );\n        HarmShapeFIRPacked_Q14 |= SKP_LSHIFT( ( SKP_int32 )SKP_RSHIFT( HarmShapeGain_Q14[ k ], 1 ), 16 );\n\n        NSQ->rewhite_flag = 0;\n        if( psEncCtrlC->sigtype == SIG_TYPE_VOICED ) {\n            /* Voiced */\n            lag = psEncCtrlC->pitchL[ k ];\n\n            /* Re-whitening */\n            if( ( k & ( 3 - SKP_LSHIFT( LSF_interpolation_flag, 1 ) ) ) == 0 ) {\n\n                /* Rewhiten with new A coefs */\n                start_idx = psEncC->frame_length - lag - psEncC->predictLPCOrder - LTP_ORDER / 2;\n                SKP_assert( start_idx >= 0 );\n                SKP_assert( start_idx <= psEncC->frame_length - psEncC->predictLPCOrder );\n\n                SKP_memset( FiltState, 0, psEncC->predictLPCOrder * sizeof( SKP_int32 ) );\n                SKP_Silk_MA_Prediction( &NSQ->xq[ start_idx + k * ( psEncC->frame_length >> 2 ) ], \n                    A_Q12, FiltState, sLTP + start_idx, psEncC->frame_length - start_idx, psEncC->predictLPCOrder );\n\n                NSQ->rewhite_flag = 1;\n                NSQ->sLTP_buf_idx = psEncC->frame_length;\n            }\n        }\n        \n        SKP_Silk_nsq_scale_states( NSQ, x, x_sc_Q10, psEncC->subfr_length, sLTP, \n            sLTP_Q16, k, LTP_scale_Q14, Gains_Q16, psEncCtrlC->pitchL );\n\n        SKP_Silk_noise_shape_quantizer( NSQ, psEncCtrlC->sigtype, x_sc_Q10, q, pxq, sLTP_Q16, A_Q12, B_Q14, \n            AR_shp_Q13, lag, HarmShapeFIRPacked_Q14, Tilt_Q14[ k ], LF_shp_Q14[ k ], Gains_Q16[ k ], Lambda_Q10, \n            offset_Q10, psEncC->subfr_length, psEncC->shapingLPCOrder, psEncC->predictLPCOrder\n        );\n\n        x          += psEncC->subfr_length;\n        q          += psEncC->subfr_length;\n        pxq        += psEncC->subfr_length;\n    }\n\n    /* Update lagPrev for next frame */\n    NSQ->lagPrev = psEncCtrlC->pitchL[ NB_SUBFR - 1 ];\n\n    /* Save quantized speech and noise shaping signals */\n    SKP_memcpy( NSQ->xq,           &NSQ->xq[           psEncC->frame_length ], psEncC->frame_length * sizeof( SKP_int16 ) );\n    SKP_memcpy( NSQ->sLTP_shp_Q10, &NSQ->sLTP_shp_Q10[ psEncC->frame_length ], psEncC->frame_length * sizeof( SKP_int32 ) );\n\n#ifdef USE_UNQUANTIZED_LSFS\n    DEBUG_STORE_DATA( xq_unq_lsfs.pcm, NSQ->xq, psEncC->frame_length * sizeof( SKP_int16 ) );\n#endif\n\n}\n\n/***********************************/\n/* SKP_Silk_noise_shape_quantizer  */\n/***********************************/\nSKP_INLINE void SKP_Silk_noise_shape_quantizer(\n    SKP_Silk_nsq_state  *NSQ,               /* I/O  NSQ state                       */\n    SKP_int             sigtype,            /* I    Signal type                     */\n    const SKP_int32     x_sc_Q10[],         /* I                                    */\n    SKP_int8            q[],                /* O                                    */\n    SKP_int16           xq[],               /* O                                    */\n    SKP_int32           sLTP_Q16[],         /* I/O  LTP state                       */\n    const SKP_int16     a_Q12[],            /* I    Short term prediction coefs     */\n    const SKP_int16     b_Q14[],            /* I    Long term prediction coefs      */\n    const SKP_int16     AR_shp_Q13[],       /* I    Noise shaping AR coefs          */\n    SKP_int             lag,                /* I    Pitch lag                       */\n    SKP_int32           HarmShapeFIRPacked_Q14, /* I                                */\n    SKP_int             Tilt_Q14,           /* I    Spectral tilt                   */\n    SKP_int32           LF_shp_Q14,         /* I                                    */\n    SKP_int32           Gain_Q16,           /* I                                    */\n    SKP_int             Lambda_Q10,         /* I                                    */\n    SKP_int             offset_Q10,         /* I                                    */\n    SKP_int             length,             /* I    Input length                    */\n    SKP_int             shapingLPCOrder,    /* I    Noise shaping AR filter order   */\n    SKP_int             predictLPCOrder     /* I    Prediction filter order         */\n)\n{\n    SKP_int     i, j;\n    SKP_int32   LTP_pred_Q14, LPC_pred_Q10, n_AR_Q10, n_LTP_Q14;\n    SKP_int32   n_LF_Q10, r_Q10, q_Q0, q_Q10;\n    SKP_int32   thr1_Q10, thr2_Q10, thr3_Q10;\n    SKP_int32   dither, exc_Q10, LPC_exc_Q10, xq_Q10;\n    SKP_int32   tmp1, tmp2, sLF_AR_shp_Q10;\n    SKP_int32   *psLPC_Q14, *shp_lag_ptr, *pred_lag_ptr;\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n    SKP_int32   a_Q12_tmp[ MAX_LPC_ORDER / 2 ], Atmp;\n    /* Preload LPC coefficients to array on stack. Gives small performance gain */\n    SKP_memcpy( a_Q12_tmp, a_Q12, predictLPCOrder * sizeof( SKP_int16 ) );\n#endif\n\n    shp_lag_ptr  = &NSQ->sLTP_shp_Q10[ NSQ->sLTP_shp_buf_idx - lag + HARM_SHAPE_FIR_TAPS / 2 ];\n    pred_lag_ptr = &sLTP_Q16[ NSQ->sLTP_buf_idx - lag + LTP_ORDER / 2 ];\n    \n    /* Setup short term AR state */\n    psLPC_Q14 = &NSQ->sLPC_Q14[ NSQ_LPC_BUF_LENGTH - 1 ];\n\n    /* Quantization thresholds */\n    thr1_Q10 = SKP_SUB_RSHIFT32( -1536, Lambda_Q10, 1 );\n    thr2_Q10 = SKP_SUB_RSHIFT32(  -512, Lambda_Q10, 1 );\n    thr2_Q10 = SKP_ADD_RSHIFT32( thr2_Q10, SKP_SMULBB( offset_Q10, Lambda_Q10 ), 10 );\n    thr3_Q10 = SKP_ADD_RSHIFT32(   512, Lambda_Q10, 1 );\n\n    for( i = 0; i < length; i++ ) {\n        /* Generate dither */\n        NSQ->rand_seed = SKP_RAND( NSQ->rand_seed );\n\n        /* dither = rand_seed < 0 ? 0xFFFFFFFF : 0; */\n        dither = SKP_RSHIFT( NSQ->rand_seed, 31 );\n                \n        /* Short-term prediction */\n        SKP_assert( ( predictLPCOrder  & 1 ) == 0 );    /* check that order is even */\n        /* check that array starts at 4-byte aligned address */\n        SKP_assert( ( ( SKP_int64 )( ( SKP_int8* )a_Q12 - ( SKP_int8* )0 ) & 3 ) == 0 );\n        SKP_assert( predictLPCOrder >= 10 );            /* check that unrolling works */\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n        /* NOTE: the code below loads two int16 values in an int32, and multiplies each using the   */\n        /* SMLAWB and SMLAWT instructions. On a big-endian CPU the two int16 variables would be     */\n        /* loaded in reverse order and the code will give the wrong result. In that case swapping   */\n        /* the SMLAWB and SMLAWT instructions should solve the problem.                             */\n        /* Partially unrolled */\n        Atmp = a_Q12_tmp[ 0 ];      /* read two coefficients at once */\n        LPC_pred_Q10 = SKP_SMULWB(               psLPC_Q14[  0 ], Atmp );\n        LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psLPC_Q14[ -1 ], Atmp );\n        Atmp = a_Q12_tmp[ 1 ];\n        LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -2 ], Atmp );\n        LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psLPC_Q14[ -3 ], Atmp );\n        Atmp = a_Q12_tmp[ 2 ];\n        LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -4 ], Atmp );\n        LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psLPC_Q14[ -5 ], Atmp );\n        Atmp = a_Q12_tmp[ 3 ];\n        LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -6 ], Atmp );\n        LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psLPC_Q14[ -7 ], Atmp );\n        Atmp = a_Q12_tmp[ 4 ];\n        LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -8 ], Atmp );\n        LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psLPC_Q14[ -9 ], Atmp );\n        for( j = 10; j < predictLPCOrder; j += 2 ) {\n            Atmp = a_Q12_tmp[ j >> 1 ];     /* read two coefficients at once */\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -j     ], Atmp );\n            LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psLPC_Q14[ -j - 1 ], Atmp );\n        }\n#else\n        /* Partially unrolled */\n        LPC_pred_Q10 = SKP_SMULWB(               psLPC_Q14[  0 ], a_Q12[ 0 ] );\n        LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -1 ], a_Q12[ 1 ] );\n        LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -2 ], a_Q12[ 2 ] );\n        LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -3 ], a_Q12[ 3 ] );\n        LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -4 ], a_Q12[ 4 ] );\n        LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -5 ], a_Q12[ 5 ] );\n        LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -6 ], a_Q12[ 6 ] );\n        LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -7 ], a_Q12[ 7 ] );\n        LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -8 ], a_Q12[ 8 ] );\n        LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -9 ], a_Q12[ 9 ] );\n        for( j = 10; j < predictLPCOrder; j ++ ) {\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -j ], a_Q12[ j ] );\n        }\n#endif\n        /* Long-term prediction */\n        if( sigtype == SIG_TYPE_VOICED ) {\n            /* Unrolled loop */\n            LTP_pred_Q14 = SKP_SMULWB(               pred_lag_ptr[  0 ], b_Q14[ 0 ] );\n            LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -1 ], b_Q14[ 1 ] );\n            LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -2 ], b_Q14[ 2 ] );\n            LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -3 ], b_Q14[ 3 ] );\n            LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -4 ], b_Q14[ 4 ] );\n            pred_lag_ptr++;\n        } else {\n            LTP_pred_Q14 = 0;\n        }\n\n        /* Noise shape feedback */\n        SKP_assert( ( shapingLPCOrder & 1 ) == 0 );   /* check that order is even */\n        tmp2 = psLPC_Q14[ 0 ];\n        tmp1 = NSQ->sAR2_Q14[ 0 ];\n        NSQ->sAR2_Q14[ 0 ] = tmp2;\n        n_AR_Q10 = SKP_SMULWB( tmp2, AR_shp_Q13[ 0 ] );\n        for( j = 2; j < shapingLPCOrder; j += 2 ) {\n            tmp2 = NSQ->sAR2_Q14[ j - 1 ];\n            NSQ->sAR2_Q14[ j - 1 ] = tmp1;\n            n_AR_Q10 = SKP_SMLAWB( n_AR_Q10, tmp1, AR_shp_Q13[ j - 1 ] );\n            tmp1 = NSQ->sAR2_Q14[ j + 0 ];\n            NSQ->sAR2_Q14[ j + 0 ] = tmp2;\n            n_AR_Q10 = SKP_SMLAWB( n_AR_Q10, tmp2, AR_shp_Q13[ j ] );\n        }\n        NSQ->sAR2_Q14[ shapingLPCOrder - 1 ] = tmp1;\n        n_AR_Q10 = SKP_SMLAWB( n_AR_Q10, tmp1, AR_shp_Q13[ shapingLPCOrder - 1 ] );\n\n        n_AR_Q10 = SKP_RSHIFT( n_AR_Q10, 1 );   /* Q11 -> Q10 */\n        n_AR_Q10 = SKP_SMLAWB( n_AR_Q10, NSQ->sLF_AR_shp_Q12, Tilt_Q14 );\n\n        n_LF_Q10 = SKP_LSHIFT( SKP_SMULWB( NSQ->sLTP_shp_Q10[ NSQ->sLTP_shp_buf_idx - 1 ], LF_shp_Q14 ), 2 ); \n        n_LF_Q10 = SKP_SMLAWT( n_LF_Q10, NSQ->sLF_AR_shp_Q12, LF_shp_Q14 );\n\n        SKP_assert( lag > 0 || sigtype == SIG_TYPE_UNVOICED );\n\n        /* Long-term shaping */\n        if( lag > 0 ) {\n            /* Symmetric, packed FIR coefficients */\n            n_LTP_Q14 = SKP_SMULWB( SKP_ADD32( shp_lag_ptr[ 0 ], shp_lag_ptr[ -2 ] ), HarmShapeFIRPacked_Q14 );\n            n_LTP_Q14 = SKP_SMLAWT( n_LTP_Q14, shp_lag_ptr[ -1 ],                     HarmShapeFIRPacked_Q14 );\n            n_LTP_Q14 = SKP_LSHIFT( n_LTP_Q14, 6 );\n            shp_lag_ptr++;\n        } else {\n            n_LTP_Q14 = 0;\n        }\n\n        /* Input minus prediction plus noise feedback  */\n        //r = x[ i ] - LTP_pred - LPC_pred + n_AR + n_Tilt + n_LF + n_LTP;\n        tmp1  = SKP_SUB32( LTP_pred_Q14, n_LTP_Q14 );                       /* Add Q14 stuff */\n        tmp1  = SKP_RSHIFT( tmp1, 4 );                                      /* convert to Q10  */\n        tmp1  = SKP_ADD32( tmp1, LPC_pred_Q10 );                            /* add Q10 stuff */ \n        tmp1  = SKP_SUB32( tmp1, n_AR_Q10 );                                /* subtract Q10 stuff */ \n        tmp1  = SKP_SUB32( tmp1, n_LF_Q10 );                                /* subtract Q10 stuff */ \n        r_Q10 = SKP_SUB32( x_sc_Q10[ i ], tmp1 );\n\n        /* Flip sign depending on dither */\n        r_Q10 = ( r_Q10 ^ dither ) - dither;\n        r_Q10 = SKP_SUB32( r_Q10, offset_Q10 );\n        r_Q10 = SKP_LIMIT_32( r_Q10, -64 << 10, 64 << 10 );\n\n        /* Quantize */\n        q_Q0 = 0;\n        q_Q10 = 0;\n        if( r_Q10 < thr2_Q10 ) {\n            if( r_Q10 < thr1_Q10 ) {\n                q_Q0 = SKP_RSHIFT_ROUND( SKP_ADD_RSHIFT32( r_Q10, Lambda_Q10, 1 ), 10 );\n                q_Q10 = SKP_LSHIFT( q_Q0, 10 );\n            } else {\n                q_Q0 = -1;\n                q_Q10 = -1024;\n            }\n        } else {\n            if( r_Q10 > thr3_Q10 ) {\n                q_Q0 = SKP_RSHIFT_ROUND( SKP_SUB_RSHIFT32( r_Q10, Lambda_Q10, 1 ), 10 );\n                q_Q10 = SKP_LSHIFT( q_Q0, 10 );\n            }\n        }\n        q[ i ] = ( SKP_int8 )q_Q0; /* No saturation needed because max is 64 */\n\n        /* Excitation */\n        exc_Q10 = SKP_ADD32( q_Q10, offset_Q10 );\n        exc_Q10 = ( exc_Q10 ^ dither ) - dither;\n\n        /* Add predictions */\n        LPC_exc_Q10 = SKP_ADD32( exc_Q10, SKP_RSHIFT_ROUND( LTP_pred_Q14, 4 ) );\n        xq_Q10      = SKP_ADD32( LPC_exc_Q10, LPC_pred_Q10 );\n        \n        /* Scale XQ back to normal level before saving */\n        xq[ i ] = ( SKP_int16 )SKP_SAT16( SKP_RSHIFT_ROUND( SKP_SMULWW( xq_Q10, Gain_Q16 ), 10 ) );\n        \n        \n        /* Update states */\n        psLPC_Q14++;\n        *psLPC_Q14 = SKP_LSHIFT( xq_Q10, 4 );\n        sLF_AR_shp_Q10 = SKP_SUB32( xq_Q10, n_AR_Q10 );\n        NSQ->sLF_AR_shp_Q12 = SKP_LSHIFT( sLF_AR_shp_Q10, 2 );\n\n        NSQ->sLTP_shp_Q10[ NSQ->sLTP_shp_buf_idx ] = SKP_SUB32( sLF_AR_shp_Q10, n_LF_Q10 );\n        sLTP_Q16[ NSQ->sLTP_buf_idx ] = SKP_LSHIFT( LPC_exc_Q10, 6 );\n        NSQ->sLTP_shp_buf_idx++;\n        NSQ->sLTP_buf_idx++;\n\n        /* Make dither dependent on quantized signal */\n        NSQ->rand_seed += q[ i ];\n    }\n\n    /* Update LPC synth buffer */\n    SKP_memcpy( NSQ->sLPC_Q14, &NSQ->sLPC_Q14[ length ], NSQ_LPC_BUF_LENGTH * sizeof( SKP_int32 ) );\n}\n\nSKP_INLINE void SKP_Silk_nsq_scale_states(\n    SKP_Silk_nsq_state  *NSQ,               /* I/O NSQ state                        */\n    const SKP_int16     x[],                /* I input in Q0                        */\n    SKP_int32           x_sc_Q10[],         /* O input scaled with 1/Gain           */\n    SKP_int             subfr_length,       /* I length of input                    */\n    const SKP_int16     sLTP[],             /* I re-whitened LTP state in Q0        */\n    SKP_int32           sLTP_Q16[],         /* O LTP state matching scaled input    */\n    SKP_int             subfr,              /* I subframe number                    */\n    const SKP_int       LTP_scale_Q14,      /* I                                    */\n    const SKP_int32     Gains_Q16[ NB_SUBFR ], /* I                                 */\n    const SKP_int       pitchL[ NB_SUBFR ]  /* I                                    */\n)\n{\n    SKP_int   i, lag;\n    SKP_int32 inv_gain_Q16, gain_adj_Q16, inv_gain_Q32;\n\n    inv_gain_Q16 = SKP_INVERSE32_varQ( SKP_max( Gains_Q16[ subfr ], 1 ), 32 );\n    inv_gain_Q16 = SKP_min( inv_gain_Q16, SKP_int16_MAX );\n    lag          = pitchL[ subfr ];\n\n    /* After rewhitening the LTP state is un-scaled, so scale with inv_gain_Q16 */\n    if( NSQ->rewhite_flag ) {\n        inv_gain_Q32 = SKP_LSHIFT( inv_gain_Q16, 16 );\n        if( subfr == 0 ) {\n            /* Do LTP downscaling */\n            inv_gain_Q32 = SKP_LSHIFT( SKP_SMULWB( inv_gain_Q32, LTP_scale_Q14 ), 2 );\n        }\n        for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx; i++ ) {\n            SKP_assert( i < MAX_FRAME_LENGTH );\n            sLTP_Q16[ i ] = SKP_SMULWB( inv_gain_Q32, sLTP[ i ] );\n        }\n    }\n\n    /* Adjust for changing gain */\n    if( inv_gain_Q16 != NSQ->prev_inv_gain_Q16 ) {\n        gain_adj_Q16 = SKP_DIV32_varQ( inv_gain_Q16, NSQ->prev_inv_gain_Q16, 16 );\n\n        /* Scale long-term shaping state */\n        for( i = NSQ->sLTP_shp_buf_idx - subfr_length * NB_SUBFR; i < NSQ->sLTP_shp_buf_idx; i++ ) {\n            NSQ->sLTP_shp_Q10[ i ] = SKP_SMULWW( gain_adj_Q16, NSQ->sLTP_shp_Q10[ i ] );\n        }\n\n        /* Scale long-term prediction state */\n        if( NSQ->rewhite_flag == 0 ) {\n            for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx; i++ ) {\n                sLTP_Q16[ i ] = SKP_SMULWW( gain_adj_Q16, sLTP_Q16[ i ] );\n            }\n        }\n\n        NSQ->sLF_AR_shp_Q12 = SKP_SMULWW( gain_adj_Q16, NSQ->sLF_AR_shp_Q12 );\n\n        /* Scale short-term prediction and shaping states */\n        for( i = 0; i < NSQ_LPC_BUF_LENGTH; i++ ) {\n            NSQ->sLPC_Q14[ i ] = SKP_SMULWW( gain_adj_Q16, NSQ->sLPC_Q14[ i ] );\n        }\n        for( i = 0; i < MAX_SHAPE_LPC_ORDER; i++ ) {\n            NSQ->sAR2_Q14[ i ] = SKP_SMULWW( gain_adj_Q16, NSQ->sAR2_Q14[ i ] );\n        }\n    }\n\n    /* Scale input */\n    for( i = 0; i < subfr_length; i++ ) {\n        x_sc_Q10[ i ] = SKP_RSHIFT( SKP_SMULBB( x[ i ], ( SKP_int16 )inv_gain_Q16 ), 6 );\n    }\n\n    /* save inv_gain */\n    SKP_assert( inv_gain_Q16 != 0 );\n    NSQ->prev_inv_gain_Q16 = inv_gain_Q16;\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_NSQ_del_dec.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\ntypedef struct {\n    SKP_int32 RandState[ DECISION_DELAY ];\n    SKP_int32 Q_Q10[     DECISION_DELAY ];\n    SKP_int32 Xq_Q10[    DECISION_DELAY ];\n    SKP_int32 Pred_Q16[  DECISION_DELAY ];\n    SKP_int32 Shape_Q10[ DECISION_DELAY ];\n    SKP_int32 Gain_Q16[  DECISION_DELAY ];\n    SKP_int32 sAR2_Q14[ MAX_SHAPE_LPC_ORDER ];\n    SKP_int32 sLPC_Q14[ MAX_FRAME_LENGTH / NB_SUBFR + NSQ_LPC_BUF_LENGTH ];\n    SKP_int32 LF_AR_Q12;\n    SKP_int32 Seed;\n    SKP_int32 SeedInit;\n    SKP_int32 RD_Q10;\n} NSQ_del_dec_struct;\n\ntypedef struct {\n    SKP_int32 Q_Q10;\n    SKP_int32 RD_Q10;\n    SKP_int32 xq_Q14;\n    SKP_int32 LF_AR_Q12;\n    SKP_int32 sLTP_shp_Q10;\n    SKP_int32 LPC_exc_Q16;\n} NSQ_sample_struct;\n\nSKP_INLINE void SKP_Silk_copy_del_dec_state(\n    NSQ_del_dec_struct  *DD_dst,                /* I    Dst del dec state                   */\n    NSQ_del_dec_struct  *DD_src,                /* I    Src del dec state                   */\n    SKP_int             LPC_state_idx           /* I    Index to LPC buffer                 */\n);\n\nSKP_INLINE void SKP_Silk_nsq_del_dec_scale_states(\n    SKP_Silk_nsq_state  *NSQ,                   /* I/O  NSQ state                           */\n    NSQ_del_dec_struct  psDelDec[],             /* I/O  Delayed decision states             */\n    const SKP_int16     x[],                    /* I    Input in Q0                         */\n    SKP_int32           x_sc_Q10[],             /* O    Input scaled with 1/Gain in Q10     */\n    SKP_int             subfr_length,           /* I    Length of input                     */\n    const SKP_int16     sLTP[],                 /* I    Re-whitened LTP state in Q0         */\n    SKP_int32           sLTP_Q16[],             /* O    LTP state matching scaled input     */\n    SKP_int             subfr,                  /* I    Subframe number                     */\n    SKP_int             nStatesDelayedDecision, /* I    Number of del dec states            */\n    SKP_int             smpl_buf_idx,           /* I    Index to newest samples in buffers  */\n    const SKP_int       LTP_scale_Q14,          /* I    LTP state scaling                   */\n    const SKP_int32     Gains_Q16[ NB_SUBFR ],  /* I                                        */\n    const SKP_int       pitchL[ NB_SUBFR ]      /* I    Pitch lag                           */\n);\n\n/******************************************/\n/* Noise shape quantizer for one subframe */\n/******************************************/\nSKP_INLINE void SKP_Silk_noise_shape_quantizer_del_dec(\n    SKP_Silk_nsq_state  *NSQ,                   /* I/O  NSQ state                           */\n    NSQ_del_dec_struct  psDelDec[],             /* I/O  Delayed decision states             */\n    SKP_int             sigtype,                /* I    Signal type                         */\n    const SKP_int32     x_Q10[],                /* I                                        */\n    SKP_int8            q[],                    /* O                                        */\n    SKP_int16           xq[],                   /* O                                        */\n    SKP_int32           sLTP_Q16[],             /* I/O  LTP filter state                    */\n    const SKP_int16     a_Q12[],                /* I    Short term prediction coefs         */\n    const SKP_int16     b_Q14[],                /* I    Long term prediction coefs          */\n    const SKP_int16     AR_shp_Q13[],           /* I    Noise shaping coefs                 */\n    SKP_int             lag,                    /* I    Pitch lag                           */\n    SKP_int32           HarmShapeFIRPacked_Q14, /* I                                        */\n    SKP_int             Tilt_Q14,               /* I    Spectral tilt                       */\n    SKP_int32           LF_shp_Q14,             /* I                                        */\n    SKP_int32           Gain_Q16,               /* I                                        */\n    SKP_int             Lambda_Q10,             /* I                                        */\n    SKP_int             offset_Q10,             /* I                                        */\n    SKP_int             length,                 /* I    Input length                        */\n    SKP_int             subfr,                  /* I    Subframe number                     */\n    SKP_int             shapingLPCOrder,        /* I    Shaping LPC filter order            */\n    SKP_int             predictLPCOrder,        /* I    Prediction filter order             */\n    SKP_int             warping_Q16,            /* I                                        */\n    SKP_int             nStatesDelayedDecision, /* I    Number of states in decision tree   */\n    SKP_int             *smpl_buf_idx,          /* I    Index to newest samples in buffers  */\n    SKP_int             decisionDelay           /* I                                        */\n);\n\nvoid SKP_Silk_NSQ_del_dec(\n    SKP_Silk_encoder_state          *psEncC,                                    /* I/O  Encoder State                       */\n    SKP_Silk_encoder_control        *psEncCtrlC,                                /* I    Encoder Control                     */\n    SKP_Silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                           */\n    const SKP_int16                 x[],                                        /* I    Prefiltered input signal            */\n    SKP_int8                        q[],                                        /* O    Quantized pulse signal              */\n    const SKP_int                   LSFInterpFactor_Q2,                         /* I    LSF interpolation factor in Q2      */\n    const SKP_int16                 PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Prediction coefs                    */\n    const SKP_int16                 LTPCoef_Q14[ LTP_ORDER * NB_SUBFR ],        /* I    LT prediction coefs                 */\n    const SKP_int16                 AR2_Q13[ NB_SUBFR * MAX_SHAPE_LPC_ORDER ],  /* I                                        */\n    const SKP_int                   HarmShapeGain_Q14[ NB_SUBFR ],              /* I                                        */\n    const SKP_int                   Tilt_Q14[ NB_SUBFR ],                       /* I    Spectral tilt                       */\n    const SKP_int32                 LF_shp_Q14[ NB_SUBFR ],                     /* I                                        */\n    const SKP_int32                 Gains_Q16[ NB_SUBFR ],                      /* I                                        */\n    const SKP_int                   Lambda_Q10,                                 /* I                                        */\n    const SKP_int                   LTP_scale_Q14                               /* I    LTP state scaling                   */\n)\n{\n    SKP_int     i, k, lag, start_idx, LSF_interpolation_flag, Winner_ind, subfr;\n    SKP_int     last_smple_idx, smpl_buf_idx, decisionDelay, subfr_length;\n    const SKP_int16 *A_Q12, *B_Q14, *AR_shp_Q13;\n    SKP_int16   *pxq;\n    SKP_int32   sLTP_Q16[ 2 * MAX_FRAME_LENGTH ];\n    SKP_int16   sLTP[     2 * MAX_FRAME_LENGTH ];\n    SKP_int32   HarmShapeFIRPacked_Q14;\n    SKP_int     offset_Q10;\n    SKP_int32   FiltState[ MAX_LPC_ORDER ], RDmin_Q10;\n    SKP_int32   x_sc_Q10[ MAX_FRAME_LENGTH / NB_SUBFR ];\n    NSQ_del_dec_struct psDelDec[ MAX_DEL_DEC_STATES ];\n    NSQ_del_dec_struct *psDD;\n\n    subfr_length = psEncC->frame_length / NB_SUBFR;\n\n    /* Set unvoiced lag to the previous one, overwrite later for voiced */\n    lag = NSQ->lagPrev;\n\n    SKP_assert( NSQ->prev_inv_gain_Q16 != 0 );\n\n    /* Initialize delayed decision states */\n    SKP_memset( psDelDec, 0, psEncC->nStatesDelayedDecision * sizeof( NSQ_del_dec_struct ) );\n    for( k = 0; k < psEncC->nStatesDelayedDecision; k++ ) {\n        psDD                 = &psDelDec[ k ];\n        psDD->Seed           = ( k + psEncCtrlC->Seed ) & 3;\n        psDD->SeedInit       = psDD->Seed;\n        psDD->RD_Q10         = 0;\n        psDD->LF_AR_Q12      = NSQ->sLF_AR_shp_Q12;\n        psDD->Shape_Q10[ 0 ] = NSQ->sLTP_shp_Q10[ psEncC->frame_length - 1 ];\n        SKP_memcpy( psDD->sLPC_Q14, NSQ->sLPC_Q14, NSQ_LPC_BUF_LENGTH * sizeof( SKP_int32 ) );\n        SKP_memcpy( psDD->sAR2_Q14, NSQ->sAR2_Q14, sizeof( NSQ->sAR2_Q14 ) );\n    }\n\n    offset_Q10   = SKP_Silk_Quantization_Offsets_Q10[ psEncCtrlC->sigtype ][ psEncCtrlC->QuantOffsetType ];\n    smpl_buf_idx = 0; /* index of oldest samples */\n\n    decisionDelay = SKP_min_int( DECISION_DELAY, subfr_length );\n\n    /* For voiced frames limit the decision delay to lower than the pitch lag */\n    if( psEncCtrlC->sigtype == SIG_TYPE_VOICED ) {\n        for( k = 0; k < NB_SUBFR; k++ ) {\n            decisionDelay = SKP_min_int( decisionDelay, psEncCtrlC->pitchL[ k ] - LTP_ORDER / 2 - 1 );\n        }\n    } else {\n        if( lag > 0 ) {\n            decisionDelay = SKP_min_int( decisionDelay, lag - LTP_ORDER / 2 - 1 );\n        }\n    }\n\n    if( LSFInterpFactor_Q2 == ( 1 << 2 ) ) {\n        LSF_interpolation_flag = 0;\n    } else {\n        LSF_interpolation_flag = 1;\n    }\n\n    /* Setup pointers to start of sub frame */\n    pxq                   = &NSQ->xq[ psEncC->frame_length ];\n    NSQ->sLTP_shp_buf_idx = psEncC->frame_length;\n    NSQ->sLTP_buf_idx     = psEncC->frame_length;\n    subfr = 0;\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        A_Q12      = &PredCoef_Q12[ ( ( k >> 1 ) | ( 1 - LSF_interpolation_flag ) ) * MAX_LPC_ORDER ];\n        B_Q14      = &LTPCoef_Q14[ k * LTP_ORDER           ];\n        AR_shp_Q13 = &AR2_Q13[     k * MAX_SHAPE_LPC_ORDER ];\n\n        /* Noise shape parameters */\n        SKP_assert( HarmShapeGain_Q14[ k ] >= 0 );\n        HarmShapeFIRPacked_Q14  =                          SKP_RSHIFT( HarmShapeGain_Q14[ k ], 2 );\n        HarmShapeFIRPacked_Q14 |= SKP_LSHIFT( ( SKP_int32 )SKP_RSHIFT( HarmShapeGain_Q14[ k ], 1 ), 16 );\n\n        NSQ->rewhite_flag = 0;\n        if( psEncCtrlC->sigtype == SIG_TYPE_VOICED ) {\n            /* Voiced */\n            lag = psEncCtrlC->pitchL[ k ];\n\n            /* Re-whitening */\n            if( ( k & ( 3 - SKP_LSHIFT( LSF_interpolation_flag, 1 ) ) ) == 0 ) {\n                if( k == 2 ) {\n                    /* RESET DELAYED DECISIONS */\n                    /* Find winner */\n                    RDmin_Q10 = psDelDec[ 0 ].RD_Q10;\n                    Winner_ind = 0;\n                    for( i = 1; i < psEncC->nStatesDelayedDecision; i++ ) {\n                        if( psDelDec[ i ].RD_Q10 < RDmin_Q10 ) {\n                            RDmin_Q10 = psDelDec[ i ].RD_Q10;\n                            Winner_ind = i;\n                        }\n                    }\n                    for( i = 0; i < psEncC->nStatesDelayedDecision; i++ ) {\n                        if( i != Winner_ind ) {\n                            psDelDec[ i ].RD_Q10 += ( SKP_int32_MAX >> 4 );\n                            SKP_assert( psDelDec[ i ].RD_Q10 >= 0 );\n                        }\n                    }\n                    \n                    /* Copy final part of signals from winner state to output and long-term filter states */\n                    psDD = &psDelDec[ Winner_ind ];\n                    last_smple_idx = smpl_buf_idx + decisionDelay;\n                    for( i = 0; i < decisionDelay; i++ ) {\n                        last_smple_idx = ( last_smple_idx - 1 ) & DECISION_DELAY_MASK;\n                        q[   i - decisionDelay ] = ( SKP_int8 )SKP_RSHIFT( psDD->Q_Q10[ last_smple_idx ], 10 );\n                        pxq[ i - decisionDelay ] = ( SKP_int16 )SKP_SAT16( SKP_RSHIFT_ROUND( \n                            SKP_SMULWW( psDD->Xq_Q10[ last_smple_idx ], \n                            psDD->Gain_Q16[ last_smple_idx ] ), 10 ) );\n                        NSQ->sLTP_shp_Q10[ NSQ->sLTP_shp_buf_idx - decisionDelay + i ] = psDD->Shape_Q10[ last_smple_idx ];\n                    }\n\n                    subfr = 0;\n                }\n\n                /* Rewhiten with new A coefs */\n                start_idx = psEncC->frame_length - lag - psEncC->predictLPCOrder - LTP_ORDER / 2;\n                SKP_assert( start_idx >= 0 );\n                SKP_assert( start_idx <= psEncC->frame_length - psEncC->predictLPCOrder );\n\n                SKP_memset( FiltState, 0, psEncC->predictLPCOrder * sizeof( SKP_int32 ) );\n                SKP_Silk_MA_Prediction( &NSQ->xq[ start_idx + k * psEncC->subfr_length ], \n                    A_Q12, FiltState, sLTP + start_idx, psEncC->frame_length - start_idx, psEncC->predictLPCOrder );\n\n                NSQ->sLTP_buf_idx = psEncC->frame_length;\n                NSQ->rewhite_flag = 1;\n            }\n        }\n\n        SKP_Silk_nsq_del_dec_scale_states( NSQ, psDelDec, x, x_sc_Q10, \n            subfr_length, sLTP, sLTP_Q16, k, psEncC->nStatesDelayedDecision, smpl_buf_idx,\n            LTP_scale_Q14, Gains_Q16, psEncCtrlC->pitchL );\n\n        SKP_Silk_noise_shape_quantizer_del_dec( NSQ, psDelDec, psEncCtrlC->sigtype, x_sc_Q10, q, pxq, sLTP_Q16,\n            A_Q12, B_Q14, AR_shp_Q13, lag, HarmShapeFIRPacked_Q14, Tilt_Q14[ k ], LF_shp_Q14[ k ], Gains_Q16[ k ], \n            Lambda_Q10, offset_Q10, psEncC->subfr_length, subfr++, psEncC->shapingLPCOrder, psEncC->predictLPCOrder, \n            psEncC->warping_Q16, psEncC->nStatesDelayedDecision, &smpl_buf_idx, decisionDelay );\n        \n        x   += psEncC->subfr_length;\n        q   += psEncC->subfr_length;\n        pxq += psEncC->subfr_length;\n    }\n\n    /* Find winner */\n    RDmin_Q10 = psDelDec[ 0 ].RD_Q10;\n    Winner_ind = 0;\n    for( k = 1; k < psEncC->nStatesDelayedDecision; k++ ) {\n        if( psDelDec[ k ].RD_Q10 < RDmin_Q10 ) {\n            RDmin_Q10 = psDelDec[ k ].RD_Q10;\n            Winner_ind = k;\n        }\n    }\n    \n    /* Copy final part of signals from winner state to output and long-term filter states */\n    psDD = &psDelDec[ Winner_ind ];\n    psEncCtrlC->Seed = psDD->SeedInit;\n    last_smple_idx = smpl_buf_idx + decisionDelay;\n    for( i = 0; i < decisionDelay; i++ ) {\n        last_smple_idx = ( last_smple_idx - 1 ) & DECISION_DELAY_MASK;\n        q[   i - decisionDelay ] = ( SKP_int8 )SKP_RSHIFT( psDD->Q_Q10[ last_smple_idx ], 10 );\n        pxq[ i - decisionDelay ] = ( SKP_int16 )SKP_SAT16( SKP_RSHIFT_ROUND( \n            SKP_SMULWW( psDD->Xq_Q10[ last_smple_idx ], psDD->Gain_Q16[ last_smple_idx ] ), 10 ) );\n        NSQ->sLTP_shp_Q10[ NSQ->sLTP_shp_buf_idx - decisionDelay + i ] = psDD->Shape_Q10[ last_smple_idx ];\n        sLTP_Q16[          NSQ->sLTP_buf_idx     - decisionDelay + i ] = psDD->Pred_Q16[  last_smple_idx ];\n    }\n    SKP_memcpy( NSQ->sLPC_Q14, &psDD->sLPC_Q14[ psEncC->subfr_length ], NSQ_LPC_BUF_LENGTH * sizeof( SKP_int32 ) );\n    SKP_memcpy( NSQ->sAR2_Q14, psDD->sAR2_Q14, sizeof( psDD->sAR2_Q14 ) );\n\n    /* Update states */\n    NSQ->sLF_AR_shp_Q12 = psDD->LF_AR_Q12;\n    NSQ->lagPrev        = psEncCtrlC->pitchL[ NB_SUBFR - 1 ];\n\n    /* Save quantized speech and noise shaping signals */\n    SKP_memcpy( NSQ->xq,           &NSQ->xq[           psEncC->frame_length ], psEncC->frame_length * sizeof( SKP_int16 ) );\n    SKP_memcpy( NSQ->sLTP_shp_Q10, &NSQ->sLTP_shp_Q10[ psEncC->frame_length ], psEncC->frame_length * sizeof( SKP_int32 ) );\n\n#ifdef USE_UNQUANTIZED_LSFS\n    DEBUG_STORE_DATA( xq_unq_lsfs.pcm, NSQ->xq, psEncC->frame_length * sizeof( SKP_int16 ) );\n#endif\n\n}\n\n/******************************************/\n/* Noise shape quantizer for one subframe */\n/******************************************/\nSKP_INLINE void SKP_Silk_noise_shape_quantizer_del_dec(\n    SKP_Silk_nsq_state  *NSQ,                   /* I/O  NSQ state                           */\n    NSQ_del_dec_struct  psDelDec[],             /* I/O  Delayed decision states             */\n    SKP_int             sigtype,                /* I    Signal type                         */\n    const SKP_int32     x_Q10[],                /* I                                        */\n    SKP_int8            q[],                    /* O                                        */\n    SKP_int16           xq[],                   /* O                                        */\n    SKP_int32           sLTP_Q16[],             /* I/O  LTP filter state                    */\n    const SKP_int16     a_Q12[],                /* I    Short term prediction coefs         */\n    const SKP_int16     b_Q14[],                /* I    Long term prediction coefs          */\n    const SKP_int16     AR_shp_Q13[],           /* I    Noise shaping coefs                 */\n    SKP_int             lag,                    /* I    Pitch lag                           */\n    SKP_int32           HarmShapeFIRPacked_Q14, /* I                                        */\n    SKP_int             Tilt_Q14,               /* I    Spectral tilt                       */\n    SKP_int32           LF_shp_Q14,             /* I                                        */\n    SKP_int32           Gain_Q16,               /* I                                        */\n    SKP_int             Lambda_Q10,             /* I                                        */\n    SKP_int             offset_Q10,             /* I                                        */\n    SKP_int             length,                 /* I    Input length                        */\n    SKP_int             subfr,                  /* I    Subframe number                     */\n    SKP_int             shapingLPCOrder,        /* I    Shaping LPC filter order            */\n    SKP_int             predictLPCOrder,        /* I    Prediction filter order             */\n    SKP_int             warping_Q16,            /* I                                        */\n    SKP_int             nStatesDelayedDecision, /* I    Number of states in decision tree   */\n    SKP_int             *smpl_buf_idx,          /* I    Index to newest samples in buffers  */\n    SKP_int             decisionDelay           /* I                                        */\n)\n{\n    SKP_int     i, j, k, Winner_ind, RDmin_ind, RDmax_ind, last_smple_idx;\n    SKP_int32   Winner_rand_state;\n    SKP_int32   LTP_pred_Q14, LPC_pred_Q10, n_AR_Q10, n_LTP_Q14;\n    SKP_int32   n_LF_Q10, r_Q10, rr_Q20, rd1_Q10, rd2_Q10, RDmin_Q10, RDmax_Q10;\n    SKP_int32   q1_Q10, q2_Q10, dither, exc_Q10, LPC_exc_Q10, xq_Q10;\n    SKP_int32   tmp1, tmp2, sLF_AR_shp_Q10;\n    SKP_int32   *pred_lag_ptr, *shp_lag_ptr, *psLPC_Q14;\n    NSQ_sample_struct  psSampleState[ MAX_DEL_DEC_STATES ][ 2 ];\n    NSQ_del_dec_struct *psDD;\n    NSQ_sample_struct  *psSS;\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n    SKP_int32   a_Q12_tmp[ MAX_LPC_ORDER / 2 ], Atmp;\n\n    /* Preload LPC coeficients to array on stack. Gives small performance gain */\n    SKP_memcpy( a_Q12_tmp, a_Q12, predictLPCOrder * sizeof( SKP_int16 ) );\n#endif\n\n    shp_lag_ptr  = &NSQ->sLTP_shp_Q10[ NSQ->sLTP_shp_buf_idx - lag + HARM_SHAPE_FIR_TAPS / 2 ];\n    pred_lag_ptr = &sLTP_Q16[ NSQ->sLTP_buf_idx - lag + LTP_ORDER / 2 ];\n\n    for( i = 0; i < length; i++ ) {\n        /* Perform common calculations used in all states */\n\n        /* Long-term prediction */\n        if( sigtype == SIG_TYPE_VOICED ) {\n            /* Unrolled loop */\n            LTP_pred_Q14 = SKP_SMULWB(               pred_lag_ptr[  0 ], b_Q14[ 0 ] );\n            LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -1 ], b_Q14[ 1 ] );\n            LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -2 ], b_Q14[ 2 ] );\n            LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -3 ], b_Q14[ 3 ] );\n            LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -4 ], b_Q14[ 4 ] );\n            pred_lag_ptr++;\n        } else {\n            LTP_pred_Q14 = 0;\n        }\n\n        /* Long-term shaping */\n        if( lag > 0 ) {\n            /* Symmetric, packed FIR coefficients */\n            n_LTP_Q14 = SKP_SMULWB( SKP_ADD32( shp_lag_ptr[ 0 ], shp_lag_ptr[ -2 ] ), HarmShapeFIRPacked_Q14 );\n            n_LTP_Q14 = SKP_SMLAWT( n_LTP_Q14, shp_lag_ptr[ -1 ],                     HarmShapeFIRPacked_Q14 );\n            n_LTP_Q14 = SKP_LSHIFT( n_LTP_Q14, 6 );\n            shp_lag_ptr++;\n        } else {\n            n_LTP_Q14 = 0;\n        }\n\n        for( k = 0; k < nStatesDelayedDecision; k++ ) {\n            /* Delayed decision state */\n            psDD = &psDelDec[ k ];\n\n            /* Sample state */\n            psSS = psSampleState[ k ];\n\n            /* Generate dither */\n            psDD->Seed = SKP_RAND( psDD->Seed );\n\n            /* dither = rand_seed < 0 ? 0xFFFFFFFF : 0; */\n            dither = SKP_RSHIFT( psDD->Seed, 31 );\n            \n            /* Pointer used in short term prediction and shaping */\n            psLPC_Q14 = &psDD->sLPC_Q14[ NSQ_LPC_BUF_LENGTH - 1 + i ];\n            /* Short-term prediction */\n            SKP_assert( predictLPCOrder >= 10 );            /* check that unrolling works */\n            SKP_assert( ( predictLPCOrder  & 1 ) == 0 );    /* check that order is even */\n            SKP_assert( ( ( ( int )( ( char* )( a_Q12 ) - ( ( char* ) 0 ) ) ) & 3 ) == 0 );    /* check that array starts at 4-byte aligned address */\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n            /* Partially unrolled */\n            Atmp = a_Q12_tmp[ 0 ];          /* read two coefficients at once */\n            LPC_pred_Q10 = SKP_SMULWB(               psLPC_Q14[  0 ], Atmp );\n            LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psLPC_Q14[ -1 ], Atmp );\n            Atmp = a_Q12_tmp[ 1 ];\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -2 ], Atmp );\n            LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psLPC_Q14[ -3 ], Atmp );\n            Atmp = a_Q12_tmp[ 2 ];\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -4 ], Atmp );\n            LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psLPC_Q14[ -5 ], Atmp );\n            Atmp = a_Q12_tmp[ 3 ];\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -6 ], Atmp );\n            LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psLPC_Q14[ -7 ], Atmp );\n            Atmp = a_Q12_tmp[ 4 ];\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -8 ], Atmp );\n            LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psLPC_Q14[ -9 ], Atmp );\n            for( j = 10; j < predictLPCOrder; j += 2 ) {\n                Atmp = a_Q12_tmp[ j >> 1 ]; /* read two coefficients at once */\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -j     ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psLPC_Q14[ -j - 1 ], Atmp );\n            }\n#else\n            /* Partially unrolled */\n            LPC_pred_Q10 = SKP_SMULWB(               psLPC_Q14[  0 ], a_Q12[ 0 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -1 ], a_Q12[ 1 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -2 ], a_Q12[ 2 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -3 ], a_Q12[ 3 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -4 ], a_Q12[ 4 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -5 ], a_Q12[ 5 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -6 ], a_Q12[ 6 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -7 ], a_Q12[ 7 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -8 ], a_Q12[ 8 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -9 ], a_Q12[ 9 ] );\n            for( j = 10; j < predictLPCOrder; j ++ ) {\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psLPC_Q14[ -j ], a_Q12[ j ] );\n            }\n#endif\n\n            /* Noise shape feedback */\n            SKP_assert( ( shapingLPCOrder & 1 ) == 0 );   /* check that order is even */\n            /* Output of lowpass section */\n            tmp2 = SKP_SMLAWB( psLPC_Q14[ 0 ], psDD->sAR2_Q14[ 0 ], warping_Q16 );\n            /* Output of allpass section */\n            tmp1 = SKP_SMLAWB( psDD->sAR2_Q14[ 0 ], psDD->sAR2_Q14[ 1 ] - tmp2, warping_Q16 );\n            psDD->sAR2_Q14[ 0 ] = tmp2;\n            n_AR_Q10 = SKP_SMULWB( tmp2, AR_shp_Q13[ 0 ] );\n            /* Loop over allpass sections */\n            for( j = 2; j < shapingLPCOrder; j += 2 ) {\n                /* Output of allpass section */\n                tmp2 = SKP_SMLAWB( psDD->sAR2_Q14[ j - 1 ], psDD->sAR2_Q14[ j + 0 ] - tmp1, warping_Q16 );\n                psDD->sAR2_Q14[ j - 1 ] = tmp1;\n                n_AR_Q10 = SKP_SMLAWB( n_AR_Q10, tmp1, AR_shp_Q13[ j - 1 ] );\n                /* Output of allpass section */\n                tmp1 = SKP_SMLAWB( psDD->sAR2_Q14[ j + 0 ], psDD->sAR2_Q14[ j + 1 ] - tmp2, warping_Q16 );\n                psDD->sAR2_Q14[ j + 0 ] = tmp2;\n                n_AR_Q10 = SKP_SMLAWB( n_AR_Q10, tmp2, AR_shp_Q13[ j ] );\n            }\n            psDD->sAR2_Q14[ shapingLPCOrder - 1 ] = tmp1;\n            n_AR_Q10 = SKP_SMLAWB( n_AR_Q10, tmp1, AR_shp_Q13[ shapingLPCOrder - 1 ] );\n\n            n_AR_Q10 = SKP_RSHIFT( n_AR_Q10, 1 );           /* Q11 -> Q10 */\n            n_AR_Q10 = SKP_SMLAWB( n_AR_Q10, psDD->LF_AR_Q12, Tilt_Q14 );\n\n            n_LF_Q10 = SKP_LSHIFT( SKP_SMULWB( psDD->Shape_Q10[ *smpl_buf_idx ], LF_shp_Q14 ), 2 ); \n            n_LF_Q10 = SKP_SMLAWT( n_LF_Q10, psDD->LF_AR_Q12, LF_shp_Q14 );       \n\n            /* Input minus prediction plus noise feedback                       */\n            /* r = x[ i ] - LTP_pred - LPC_pred + n_AR + n_Tilt + n_LF + n_LTP  */\n            tmp1  = SKP_SUB32( LTP_pred_Q14, n_LTP_Q14 );                       /* Add Q14 stuff */\n            tmp1  = SKP_RSHIFT( tmp1, 4 );                                      /* convert to Q10 */\n            tmp1  = SKP_ADD32( tmp1, LPC_pred_Q10 );                            /* add Q10 stuff */ \n            tmp1  = SKP_SUB32( tmp1, n_AR_Q10 );                                /* subtract Q10 stuff */ \n            tmp1  = SKP_SUB32( tmp1, n_LF_Q10 );                                /* subtract Q10 stuff */ \n            r_Q10 = SKP_SUB32( x_Q10[ i ], tmp1 );                              /* residual error Q10 */\n            \n            /* Flip sign depending on dither */\n            r_Q10 = ( r_Q10 ^ dither ) - dither;\n            r_Q10 = SKP_SUB32( r_Q10, offset_Q10 );\n            r_Q10 = SKP_LIMIT_32( r_Q10, -64 << 10, 64 << 10 );\n\n            /* Find two quantization level candidates and measure their rate-distortion */\n            if( r_Q10 < -1536 ) {\n                q1_Q10  = SKP_LSHIFT( SKP_RSHIFT_ROUND( r_Q10, 10 ), 10 );\n                r_Q10   = SKP_SUB32( r_Q10, q1_Q10 );\n                rd1_Q10 = SKP_RSHIFT( SKP_SMLABB( SKP_MUL( -SKP_ADD32( q1_Q10, offset_Q10 ), Lambda_Q10 ), r_Q10, r_Q10 ), 10 );\n                rd2_Q10 = SKP_ADD32( rd1_Q10, 1024 );\n                rd2_Q10 = SKP_SUB32( rd2_Q10, SKP_ADD_LSHIFT32( Lambda_Q10, r_Q10, 1 ) );\n                q2_Q10  = SKP_ADD32( q1_Q10, 1024 );\n            } else if( r_Q10 > 512 ) {\n                q1_Q10  = SKP_LSHIFT( SKP_RSHIFT_ROUND( r_Q10, 10 ), 10 );\n                r_Q10   = SKP_SUB32( r_Q10, q1_Q10 );\n                rd1_Q10 = SKP_RSHIFT( SKP_SMLABB( SKP_MUL( SKP_ADD32( q1_Q10, offset_Q10 ), Lambda_Q10 ), r_Q10, r_Q10 ), 10 );\n                rd2_Q10 = SKP_ADD32( rd1_Q10, 1024 );\n                rd2_Q10 = SKP_SUB32( rd2_Q10, SKP_SUB_LSHIFT32( Lambda_Q10, r_Q10, 1 ) );\n                q2_Q10  = SKP_SUB32( q1_Q10, 1024 );\n            } else {            /* r_Q10 >= -1536 && q1_Q10 <= 512 */\n                rr_Q20  = SKP_SMULBB( offset_Q10, Lambda_Q10 );\n                rd2_Q10 = SKP_RSHIFT( SKP_SMLABB( rr_Q20, r_Q10, r_Q10 ), 10 );\n                rd1_Q10 = SKP_ADD32( rd2_Q10, 1024 );\n                rd1_Q10 = SKP_ADD32( rd1_Q10, SKP_SUB_RSHIFT32( SKP_ADD_LSHIFT32( Lambda_Q10, r_Q10, 1 ), rr_Q20, 9 ) );\n                q1_Q10  = -1024;\n                q2_Q10  = 0;\n            }\n\n            if( rd1_Q10 < rd2_Q10 ) {\n                psSS[ 0 ].RD_Q10 = SKP_ADD32( psDD->RD_Q10, rd1_Q10 ); \n                psSS[ 1 ].RD_Q10 = SKP_ADD32( psDD->RD_Q10, rd2_Q10 );\n                psSS[ 0 ].Q_Q10 = q1_Q10;\n                psSS[ 1 ].Q_Q10 = q2_Q10;\n            } else {\n                psSS[ 0 ].RD_Q10 = SKP_ADD32( psDD->RD_Q10, rd2_Q10 );\n                psSS[ 1 ].RD_Q10 = SKP_ADD32( psDD->RD_Q10, rd1_Q10 );\n                psSS[ 0 ].Q_Q10 = q2_Q10;\n                psSS[ 1 ].Q_Q10 = q1_Q10;\n            }\n\n            /* Update states for best quantization */\n\n            /* Quantized excitation */\n            exc_Q10 = SKP_ADD32( offset_Q10, psSS[ 0 ].Q_Q10 );\n            exc_Q10 = ( exc_Q10 ^ dither ) - dither;\n\n            /* Add predictions */\n            LPC_exc_Q10 = exc_Q10 + SKP_RSHIFT_ROUND( LTP_pred_Q14, 4 );\n            xq_Q10      = SKP_ADD32( LPC_exc_Q10, LPC_pred_Q10 );\n\n            /* Update states */\n            sLF_AR_shp_Q10         = SKP_SUB32(  xq_Q10, n_AR_Q10 );\n            psSS[ 0 ].sLTP_shp_Q10 = SKP_SUB32(  sLF_AR_shp_Q10, n_LF_Q10 );\n            psSS[ 0 ].LF_AR_Q12    = SKP_LSHIFT( sLF_AR_shp_Q10, 2 );\n            psSS[ 0 ].xq_Q14       = SKP_LSHIFT( xq_Q10,         4 );\n            psSS[ 0 ].LPC_exc_Q16  = SKP_LSHIFT( LPC_exc_Q10,    6 );\n\n            /* Update states for second best quantization */\n\n            /* Quantized excitation */\n            exc_Q10 = SKP_ADD32( offset_Q10, psSS[ 1 ].Q_Q10 );\n            exc_Q10 = ( exc_Q10 ^ dither ) - dither;\n\n            /* Add predictions */\n            LPC_exc_Q10 = exc_Q10 + SKP_RSHIFT_ROUND( LTP_pred_Q14, 4 );\n            xq_Q10      = SKP_ADD32( LPC_exc_Q10, LPC_pred_Q10 );\n\n            /* Update states */\n            sLF_AR_shp_Q10         = SKP_SUB32(  xq_Q10, n_AR_Q10 );\n            psSS[ 1 ].sLTP_shp_Q10 = SKP_SUB32(  sLF_AR_shp_Q10, n_LF_Q10 );\n            psSS[ 1 ].LF_AR_Q12    = SKP_LSHIFT( sLF_AR_shp_Q10, 2 );\n            psSS[ 1 ].xq_Q14       = SKP_LSHIFT( xq_Q10,         4 );\n            psSS[ 1 ].LPC_exc_Q16  = SKP_LSHIFT( LPC_exc_Q10,    6 );\n        }\n\n        *smpl_buf_idx  = ( *smpl_buf_idx - 1 ) & DECISION_DELAY_MASK;                   /* Index to newest samples              */\n        last_smple_idx = ( *smpl_buf_idx + decisionDelay ) & DECISION_DELAY_MASK;       /* Index to decisionDelay old samples   */\n\n        /* Find winner */\n        RDmin_Q10 = psSampleState[ 0 ][ 0 ].RD_Q10;\n        Winner_ind = 0;\n        for( k = 1; k < nStatesDelayedDecision; k++ ) {\n            if( psSampleState[ k ][ 0 ].RD_Q10 < RDmin_Q10 ) {\n                RDmin_Q10   = psSampleState[ k ][ 0 ].RD_Q10;\n                Winner_ind = k;\n            }\n        }\n\n        /* Increase RD values of expired states */\n        Winner_rand_state = psDelDec[ Winner_ind ].RandState[ last_smple_idx ];\n        for( k = 0; k < nStatesDelayedDecision; k++ ) {\n            if( psDelDec[ k ].RandState[ last_smple_idx ] != Winner_rand_state ) {\n                psSampleState[ k ][ 0 ].RD_Q10 = SKP_ADD32( psSampleState[ k ][ 0 ].RD_Q10, ( SKP_int32_MAX >> 4 ) );\n                psSampleState[ k ][ 1 ].RD_Q10 = SKP_ADD32( psSampleState[ k ][ 1 ].RD_Q10, ( SKP_int32_MAX >> 4 ) );\n                SKP_assert( psSampleState[ k ][ 0 ].RD_Q10 >= 0 );\n            }\n        }\n\n        /* Find worst in first set and best in second set */\n        RDmax_Q10  = psSampleState[ 0 ][ 0 ].RD_Q10;\n        RDmin_Q10  = psSampleState[ 0 ][ 1 ].RD_Q10;\n        RDmax_ind = 0;\n        RDmin_ind = 0;\n        for( k = 1; k < nStatesDelayedDecision; k++ ) {\n            /* find worst in first set */\n            if( psSampleState[ k ][ 0 ].RD_Q10 > RDmax_Q10 ) {\n                RDmax_Q10  = psSampleState[ k ][ 0 ].RD_Q10;\n                RDmax_ind = k;\n            }\n            /* find best in second set */\n            if( psSampleState[ k ][ 1 ].RD_Q10 < RDmin_Q10 ) {\n                RDmin_Q10  = psSampleState[ k ][ 1 ].RD_Q10;\n                RDmin_ind = k;\n            }\n        }\n\n        /* Replace a state if best from second set outperforms worst in first set */\n        if( RDmin_Q10 < RDmax_Q10 ) {\n            SKP_Silk_copy_del_dec_state( &psDelDec[ RDmax_ind ], &psDelDec[ RDmin_ind ], i ); \n            SKP_memcpy( &psSampleState[ RDmax_ind ][ 0 ], &psSampleState[ RDmin_ind ][ 1 ], sizeof( NSQ_sample_struct ) );\n        }\n\n        /* Write samples from winner to output and long-term filter states */\n        psDD = &psDelDec[ Winner_ind ];\n        if( subfr > 0 || i >= decisionDelay ) {\n            q[  i - decisionDelay ] = ( SKP_int8 )SKP_RSHIFT( psDD->Q_Q10[ last_smple_idx ], 10 );\n            xq[ i - decisionDelay ] = ( SKP_int16 )SKP_SAT16( SKP_RSHIFT_ROUND( \n                SKP_SMULWW( psDD->Xq_Q10[ last_smple_idx ], psDD->Gain_Q16[ last_smple_idx ] ), 10 ) );\n            NSQ->sLTP_shp_Q10[ NSQ->sLTP_shp_buf_idx - decisionDelay ] = psDD->Shape_Q10[ last_smple_idx ];\n            sLTP_Q16[          NSQ->sLTP_buf_idx     - decisionDelay ] = psDD->Pred_Q16[  last_smple_idx ];\n        }\n        NSQ->sLTP_shp_buf_idx++;\n        NSQ->sLTP_buf_idx++;\n\n        /* Update states */\n        for( k = 0; k < nStatesDelayedDecision; k++ ) {\n            psDD                                     = &psDelDec[ k ];\n            psSS                                     = &psSampleState[ k ][ 0 ];\n            psDD->LF_AR_Q12                          = psSS->LF_AR_Q12;\n            psDD->sLPC_Q14[ NSQ_LPC_BUF_LENGTH + i ] = psSS->xq_Q14;\n            psDD->Xq_Q10[    *smpl_buf_idx ]         = SKP_RSHIFT( psSS->xq_Q14, 4 );\n            psDD->Q_Q10[     *smpl_buf_idx ]         = psSS->Q_Q10;\n            psDD->Pred_Q16[  *smpl_buf_idx ]         = psSS->LPC_exc_Q16;\n            psDD->Shape_Q10[ *smpl_buf_idx ]         = psSS->sLTP_shp_Q10;\n            psDD->Seed                               = SKP_ADD_RSHIFT32( psDD->Seed, psSS->Q_Q10, 10 );\n            psDD->RandState[ *smpl_buf_idx ]         = psDD->Seed;\n            psDD->RD_Q10                             = psSS->RD_Q10;\n            psDD->Gain_Q16[  *smpl_buf_idx ]         = Gain_Q16;\n        }\n    }\n    /* Update LPC states */\n    for( k = 0; k < nStatesDelayedDecision; k++ ) {\n        psDD = &psDelDec[ k ];\n        SKP_memcpy( psDD->sLPC_Q14, &psDD->sLPC_Q14[ length ], NSQ_LPC_BUF_LENGTH * sizeof( SKP_int32 ) );\n    }\n}\n\nSKP_INLINE void SKP_Silk_nsq_del_dec_scale_states(\n    SKP_Silk_nsq_state  *NSQ,                   /* I/O  NSQ state                           */\n    NSQ_del_dec_struct  psDelDec[],             /* I/O  Delayed decision states             */\n    const SKP_int16     x[],                    /* I    Input in Q0                         */\n    SKP_int32           x_sc_Q10[],             /* O    Input scaled with 1/Gain in Q10     */\n    SKP_int             subfr_length,           /* I    Length of input                     */\n    const SKP_int16     sLTP[],                 /* I    Re-whitened LTP state in Q0         */\n    SKP_int32           sLTP_Q16[],             /* O    LTP state matching scaled input     */\n    SKP_int             subfr,                  /* I    Subframe number                     */\n    SKP_int             nStatesDelayedDecision, /* I    Number of del dec states            */\n    SKP_int             smpl_buf_idx,           /* I    Index to newest samples in buffers  */\n    const SKP_int       LTP_scale_Q14,          /* I    LTP state scaling                   */\n    const SKP_int32     Gains_Q16[ NB_SUBFR ],  /* I                                        */\n    const SKP_int       pitchL[ NB_SUBFR ]      /* I    Pitch lag                           */\n)\n{\n    SKP_int            i, k, lag;\n    SKP_int32          inv_gain_Q16, gain_adj_Q16, inv_gain_Q32;\n    NSQ_del_dec_struct *psDD;\n\n    inv_gain_Q16 = SKP_INVERSE32_varQ( SKP_max( Gains_Q16[ subfr ], 1 ), 32 );\n    inv_gain_Q16 = SKP_min( inv_gain_Q16, SKP_int16_MAX );\n    lag          = pitchL[ subfr ];\n\n    /* After rewhitening the LTP state is un-scaled, so scale with inv_gain_Q16 */\n    if( NSQ->rewhite_flag ) {\n        inv_gain_Q32 = SKP_LSHIFT( inv_gain_Q16, 16 );\n        if( subfr == 0 ) {\n            /* Do LTP downscaling */\n            inv_gain_Q32 = SKP_LSHIFT( SKP_SMULWB( inv_gain_Q32, LTP_scale_Q14 ), 2 );\n        }\n        for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx; i++ ) {\n            SKP_assert( i < MAX_FRAME_LENGTH );\n            sLTP_Q16[ i ] = SKP_SMULWB( inv_gain_Q32, sLTP[ i ] );\n        }\n    }\n\n    /* Adjust for changing gain */\n    if( inv_gain_Q16 != NSQ->prev_inv_gain_Q16 ) {\n        gain_adj_Q16 = SKP_DIV32_varQ( inv_gain_Q16, NSQ->prev_inv_gain_Q16, 16 );\n\n        /* Scale long-term shaping state */\n        for( i = NSQ->sLTP_shp_buf_idx - subfr_length * NB_SUBFR; i < NSQ->sLTP_shp_buf_idx; i++ ) {\n            NSQ->sLTP_shp_Q10[ i ] = SKP_SMULWW( gain_adj_Q16, NSQ->sLTP_shp_Q10[ i ] );\n        }\n\n        /* Scale long-term prediction state */\n        if( NSQ->rewhite_flag == 0 ) {\n            for( i = NSQ->sLTP_buf_idx - lag - LTP_ORDER / 2; i < NSQ->sLTP_buf_idx; i++ ) {\n                sLTP_Q16[ i ] = SKP_SMULWW( gain_adj_Q16, sLTP_Q16[ i ] );\n            }\n        }\n\n        for( k = 0; k < nStatesDelayedDecision; k++ ) {\n            psDD = &psDelDec[ k ];\n            \n            /* Scale scalar states */\n            psDD->LF_AR_Q12 = SKP_SMULWW( gain_adj_Q16, psDD->LF_AR_Q12 );\n            \n\t        /* Scale short-term prediction and shaping states */\n            for( i = 0; i < NSQ_LPC_BUF_LENGTH; i++ ) {\n                psDD->sLPC_Q14[ i ] = SKP_SMULWW( gain_adj_Q16, psDD->sLPC_Q14[ i ] );\n            }\n            for( i = 0; i < MAX_SHAPE_LPC_ORDER; i++ ) {\n                psDD->sAR2_Q14[ i ] = SKP_SMULWW( gain_adj_Q16, psDD->sAR2_Q14[ i ] );\n            }\n            for( i = 0; i < DECISION_DELAY; i++ ) {\n                psDD->Pred_Q16[  i ] = SKP_SMULWW( gain_adj_Q16, psDD->Pred_Q16[  i ] );\n                psDD->Shape_Q10[ i ] = SKP_SMULWW( gain_adj_Q16, psDD->Shape_Q10[ i ] );\n            }\n        }\n    }\n\n    /* Scale input */\n    for( i = 0; i < subfr_length; i++ ) {\n        x_sc_Q10[ i ] = SKP_RSHIFT( SKP_SMULBB( x[ i ], ( SKP_int16 )inv_gain_Q16 ), 6 );\n    }\n\n    /* save inv_gain */\n    SKP_assert( inv_gain_Q16 != 0 );\n    NSQ->prev_inv_gain_Q16 = inv_gain_Q16;\n}\n\nSKP_INLINE void SKP_Silk_copy_del_dec_state(\n    NSQ_del_dec_struct  *DD_dst,                /* I    Dst del dec state                   */\n    NSQ_del_dec_struct  *DD_src,                /* I    Src del dec state                   */\n    SKP_int             LPC_state_idx           /* I    Index to LPC buffer                 */\n)\n{\n    SKP_memcpy( DD_dst->RandState, DD_src->RandState, sizeof( DD_src->RandState ) );\n    SKP_memcpy( DD_dst->Q_Q10,     DD_src->Q_Q10,     sizeof( DD_src->Q_Q10     ) );\n    SKP_memcpy( DD_dst->Pred_Q16,  DD_src->Pred_Q16,  sizeof( DD_src->Pred_Q16  ) );\n    SKP_memcpy( DD_dst->Shape_Q10, DD_src->Shape_Q10, sizeof( DD_src->Shape_Q10 ) );\n    SKP_memcpy( DD_dst->Xq_Q10,    DD_src->Xq_Q10,    sizeof( DD_src->Xq_Q10    ) );\n    SKP_memcpy( DD_dst->sAR2_Q14,  DD_src->sAR2_Q14,  sizeof( DD_src->sAR2_Q14  ) );\n    SKP_memcpy( &DD_dst->sLPC_Q14[ LPC_state_idx ], &DD_src->sLPC_Q14[ LPC_state_idx ], NSQ_LPC_BUF_LENGTH * sizeof( SKP_int32 ) );\n    DD_dst->LF_AR_Q12 = DD_src->LF_AR_Q12;\n    DD_dst->Seed      = DD_src->Seed;\n    DD_dst->SeedInit  = DD_src->SeedInit;\n    DD_dst->RD_Q10    = DD_src->RD_Q10;\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_PLC.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n#include \"SKP_Silk_PLC.h\"\n\n#define NB_ATT 2\nstatic const SKP_int16 HARM_ATT_Q15[NB_ATT]              = { 32440, 31130 }; /* 0.99, 0.95 */\nstatic const SKP_int16 PLC_RAND_ATTENUATE_V_Q15[NB_ATT]  = { 31130, 26214 }; /* 0.95, 0.8 */\nstatic const SKP_int16 PLC_RAND_ATTENUATE_UV_Q15[NB_ATT] = { 32440, 29491 }; /* 0.99, 0.9 */\n\nvoid SKP_Silk_PLC_Reset(\n    SKP_Silk_decoder_state      *psDec              /* I/O Decoder state        */\n)\n{\n    psDec->sPLC.pitchL_Q8 = SKP_RSHIFT( psDec->frame_length, 1 );\n}\n\nvoid SKP_Silk_PLC(\n    SKP_Silk_decoder_state      *psDec,             /* I Decoder state          */\n    SKP_Silk_decoder_control    *psDecCtrl,         /* I Decoder control        */\n    SKP_int16                   signal[],           /* O Concealed signal       */\n    SKP_int                     length,             /* I length of residual     */\n    SKP_int                     lost                /* I Loss flag              */\n)\n{\n    /* PLC control function */\n    if( psDec->fs_kHz != psDec->sPLC.fs_kHz ) {\n        SKP_Silk_PLC_Reset( psDec );\n        psDec->sPLC.fs_kHz = psDec->fs_kHz;\n    }\n\n    if( lost ) {\n        /****************************/\n        /* Generate Signal          */\n        /****************************/\n        SKP_Silk_PLC_conceal( psDec, psDecCtrl, signal, length );\n\n        psDec->lossCnt++;\n    } else {\n        /****************************/\n        /* Update state             */\n        /****************************/\n        SKP_Silk_PLC_update( psDec, psDecCtrl, signal, length );\n    }\n}\n\n/**************************************************/\n/* Update state of PLC                            */\n/**************************************************/\nvoid SKP_Silk_PLC_update(\n    SKP_Silk_decoder_state      *psDec,             /* (I/O) Decoder state          */\n    SKP_Silk_decoder_control    *psDecCtrl,         /* (I/O) Decoder control        */\n    SKP_int16                   signal[],\n    SKP_int                     length\n)\n{\n    SKP_int32 LTP_Gain_Q14, temp_LTP_Gain_Q14;\n    SKP_int   i, j;\n    SKP_Silk_PLC_struct *psPLC;\n\n    psPLC = &psDec->sPLC;\n\n    /* Update parameters used in case of packet loss */\n    psDec->prev_sigtype = psDecCtrl->sigtype;\n    LTP_Gain_Q14 = 0;\n    if( psDecCtrl->sigtype == SIG_TYPE_VOICED ) {\n        /* Find the parameters for the last subframe which contains a pitch pulse */\n        for( j = 0; j * psDec->subfr_length  < psDecCtrl->pitchL[ NB_SUBFR - 1 ]; j++ ) {\n            temp_LTP_Gain_Q14 = 0;\n            for( i = 0; i < LTP_ORDER; i++ ) {\n                temp_LTP_Gain_Q14 += psDecCtrl->LTPCoef_Q14[ ( NB_SUBFR - 1 - j ) * LTP_ORDER  + i ];\n            }\n            if( temp_LTP_Gain_Q14 > LTP_Gain_Q14 ) {\n                LTP_Gain_Q14 = temp_LTP_Gain_Q14;\n                SKP_memcpy( psPLC->LTPCoef_Q14,\n                    &psDecCtrl->LTPCoef_Q14[ SKP_SMULBB( NB_SUBFR - 1 - j, LTP_ORDER ) ],\n                    LTP_ORDER * sizeof( SKP_int16 ) );\n\n                psPLC->pitchL_Q8 = SKP_LSHIFT( psDecCtrl->pitchL[ NB_SUBFR - 1 - j ], 8 );\n            }\n        }\n\n#if USE_SINGLE_TAP\n        SKP_memset( psPLC->LTPCoef_Q14, 0, LTP_ORDER * sizeof( SKP_int16 ) );\n        psPLC->LTPCoef_Q14[ LTP_ORDER / 2 ] = LTP_Gain_Q14;\n#endif\n\n        /* Limit LT coefs */\n        if( LTP_Gain_Q14 < V_PITCH_GAIN_START_MIN_Q14 ) {\n            SKP_int   scale_Q10;\n            SKP_int32 tmp;\n\n            tmp = SKP_LSHIFT( V_PITCH_GAIN_START_MIN_Q14, 10 );\n            scale_Q10 = SKP_DIV32( tmp, SKP_max( LTP_Gain_Q14, 1 ) );\n            for( i = 0; i < LTP_ORDER; i++ ) {\n                psPLC->LTPCoef_Q14[ i ] = SKP_RSHIFT( SKP_SMULBB( psPLC->LTPCoef_Q14[ i ], scale_Q10 ), 10 );\n            }\n        } else if( LTP_Gain_Q14 > V_PITCH_GAIN_START_MAX_Q14 ) {\n            SKP_int   scale_Q14;\n            SKP_int32 tmp;\n\n            tmp = SKP_LSHIFT( V_PITCH_GAIN_START_MAX_Q14, 14 );\n            scale_Q14 = SKP_DIV32( tmp, SKP_max( LTP_Gain_Q14, 1 ) );\n            for( i = 0; i < LTP_ORDER; i++ ) {\n                psPLC->LTPCoef_Q14[ i ] = SKP_RSHIFT( SKP_SMULBB( psPLC->LTPCoef_Q14[ i ], scale_Q14 ), 14 );\n            }\n        }\n    } else {\n        psPLC->pitchL_Q8 = SKP_LSHIFT( SKP_SMULBB( psDec->fs_kHz, 18 ), 8 );\n        SKP_memset( psPLC->LTPCoef_Q14, 0, LTP_ORDER * sizeof( SKP_int16 ));\n    }\n\n    /* Save LPC coeficients */\n    SKP_memcpy( psPLC->prevLPC_Q12, psDecCtrl->PredCoef_Q12[ 1 ], psDec->LPC_order * sizeof( SKP_int16 ) );\n    psPLC->prevLTP_scale_Q14 = psDecCtrl->LTP_scale_Q14;\n\n    /* Save Gains */\n    SKP_memcpy( psPLC->prevGain_Q16, psDecCtrl->Gains_Q16, NB_SUBFR * sizeof( SKP_int32 ) );\n}\n\nvoid SKP_Silk_PLC_conceal(\n    SKP_Silk_decoder_state      *psDec,             /* I/O Decoder state */\n    SKP_Silk_decoder_control    *psDecCtrl,         /* I/O Decoder control */\n    SKP_int16                   signal[],           /* O concealed signal */\n    SKP_int                     length              /* I length of residual */\n)\n{\n    SKP_int   i, j, k;\n    SKP_int16 *B_Q14, exc_buf[ MAX_FRAME_LENGTH ], *exc_buf_ptr;\n    SKP_int16 rand_scale_Q14;\n    union {\n        SKP_int16 as_int16[ MAX_LPC_ORDER ];\n        SKP_int32 as_int32[ MAX_LPC_ORDER / 2 ];\n    } A_Q12_tmp;\n    SKP_int32 rand_seed, harm_Gain_Q15, rand_Gain_Q15;\n    SKP_int   lag, idx, sLTP_buf_idx, shift1, shift2;\n    SKP_int32 energy1, energy2, *rand_ptr, *pred_lag_ptr;\n    SKP_int32 sig_Q10[ MAX_FRAME_LENGTH ], *sig_Q10_ptr, LPC_exc_Q10, LPC_pred_Q10,  LTP_pred_Q14;\n    SKP_Silk_PLC_struct *psPLC;\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n    SKP_int32 Atmp;\n#endif\n    psPLC = &psDec->sPLC;\n\n    /* Update LTP buffer */\n    SKP_memcpy( psDec->sLTP_Q16, &psDec->sLTP_Q16[ psDec->frame_length ], psDec->frame_length * sizeof( SKP_int32 ) );\n\n    /* LPC concealment. Apply BWE to previous LPC */\n    SKP_Silk_bwexpander( psPLC->prevLPC_Q12, psDec->LPC_order, BWE_COEF_Q16 );\n\n    /* Find random noise component */\n    /* Scale previous excitation signal */\n    exc_buf_ptr = exc_buf;\n    for( k = ( NB_SUBFR >> 1 ); k < NB_SUBFR; k++ ) {\n        for( i = 0; i < psDec->subfr_length; i++ ) {\n            exc_buf_ptr[ i ] = ( SKP_int16 )SKP_RSHIFT( \n                SKP_SMULWW( psDec->exc_Q10[ i + k * psDec->subfr_length ], psPLC->prevGain_Q16[ k ] ), 10 );\n        }\n        exc_buf_ptr += psDec->subfr_length;\n    }\n    /* Find the subframe with lowest energy of the last two and use that as random noise generator */ \n    SKP_Silk_sum_sqr_shift( &energy1, &shift1, exc_buf,                         psDec->subfr_length );\n    SKP_Silk_sum_sqr_shift( &energy2, &shift2, &exc_buf[ psDec->subfr_length ], psDec->subfr_length );\n        \n    if( SKP_RSHIFT( energy1, shift2 ) < SKP_RSHIFT( energy2, shift1 ) ) {\n        /* First sub-frame has lowest energy */\n        rand_ptr = &psDec->exc_Q10[ SKP_max_int( 0, 3 * psDec->subfr_length - RAND_BUF_SIZE ) ];\n    } else {\n        /* Second sub-frame has lowest energy */\n        rand_ptr = &psDec->exc_Q10[ SKP_max_int( 0, psDec->frame_length - RAND_BUF_SIZE ) ];\n    }\n\n    /* Setup Gain to random noise component */ \n    B_Q14          = psPLC->LTPCoef_Q14;\n    rand_scale_Q14 = psPLC->randScale_Q14;\n\n    /* Setup attenuation gains */\n    harm_Gain_Q15 = HARM_ATT_Q15[ SKP_min_int( NB_ATT - 1, psDec->lossCnt ) ];\n    if( psDec->prev_sigtype == SIG_TYPE_VOICED ) {\n        rand_Gain_Q15 = PLC_RAND_ATTENUATE_V_Q15[  SKP_min_int( NB_ATT - 1, psDec->lossCnt ) ];\n    } else {\n        rand_Gain_Q15 = PLC_RAND_ATTENUATE_UV_Q15[ SKP_min_int( NB_ATT - 1, psDec->lossCnt ) ];\n    }\n\n    /* First Lost frame */\n    if( psDec->lossCnt == 0 ) {\n        rand_scale_Q14 = (1 << 14 );\n    \n        /* Reduce random noise Gain for voiced frames */\n        if( psDec->prev_sigtype == SIG_TYPE_VOICED ) {\n            for( i = 0; i < LTP_ORDER; i++ ) {\n                rand_scale_Q14 -= B_Q14[ i ];\n            }\n            rand_scale_Q14 = SKP_max_16( 3277, rand_scale_Q14 ); /* 0.2 */\n            rand_scale_Q14 = ( SKP_int16 )SKP_RSHIFT( SKP_SMULBB( rand_scale_Q14, psPLC->prevLTP_scale_Q14 ), 14 );\n        }\n\n        /* Reduce random noise for unvoiced frames with high LPC gain */\n        if( psDec->prev_sigtype == SIG_TYPE_UNVOICED ) {\n            SKP_int32 invGain_Q30, down_scale_Q30;\n            \n            SKP_Silk_LPC_inverse_pred_gain( &invGain_Q30, psPLC->prevLPC_Q12, psDec->LPC_order );\n            \n            down_scale_Q30 = SKP_min_32( SKP_RSHIFT( ( 1 << 30 ), LOG2_INV_LPC_GAIN_HIGH_THRES ), invGain_Q30 );\n            down_scale_Q30 = SKP_max_32( SKP_RSHIFT( ( 1 << 30 ), LOG2_INV_LPC_GAIN_LOW_THRES ), down_scale_Q30 );\n            down_scale_Q30 = SKP_LSHIFT( down_scale_Q30, LOG2_INV_LPC_GAIN_HIGH_THRES );\n            \n            rand_Gain_Q15 = SKP_RSHIFT( SKP_SMULWB( down_scale_Q30, rand_Gain_Q15 ), 14 );\n        }\n    }\n\n    rand_seed    = psPLC->rand_seed;\n    lag          = SKP_RSHIFT_ROUND( psPLC->pitchL_Q8, 8 );\n    sLTP_buf_idx = psDec->frame_length;\n\n    /***************************/\n    /* LTP synthesis filtering */\n    /***************************/\n    sig_Q10_ptr = sig_Q10;\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        /* Setup pointer */\n        pred_lag_ptr = &psDec->sLTP_Q16[ sLTP_buf_idx - lag + LTP_ORDER / 2 ];\n        for( i = 0; i < psDec->subfr_length; i++ ) {\n            rand_seed = SKP_RAND( rand_seed );\n            idx = SKP_RSHIFT( rand_seed, 25 ) & RAND_BUF_MASK;\n\n            /* Unrolled loop */\n            LTP_pred_Q14 = SKP_SMULWB(               pred_lag_ptr[  0 ], B_Q14[ 0 ] );\n            LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -1 ], B_Q14[ 1 ] );\n            LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -2 ], B_Q14[ 2 ] );\n            LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -3 ], B_Q14[ 3 ] );\n            LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -4 ], B_Q14[ 4 ] );\n            pred_lag_ptr++;\n            \n            /* Generate LPC residual */\n            LPC_exc_Q10 = SKP_LSHIFT( SKP_SMULWB( rand_ptr[ idx ], rand_scale_Q14 ), 2 ); /* Random noise part */\n            LPC_exc_Q10 = SKP_ADD32( LPC_exc_Q10, SKP_RSHIFT_ROUND( LTP_pred_Q14, 4 ) );  /* Harmonic part */\n            \n            /* Update states */\n            psDec->sLTP_Q16[ sLTP_buf_idx ] = SKP_LSHIFT( LPC_exc_Q10, 6 );\n            sLTP_buf_idx++;\n                \n            /* Save LPC residual */\n            sig_Q10_ptr[ i ] = LPC_exc_Q10;\n        }\n        sig_Q10_ptr += psDec->subfr_length;\n        /* Gradually reduce LTP gain */\n        for( j = 0; j < LTP_ORDER; j++ ) {\n            B_Q14[ j ] = SKP_RSHIFT( SKP_SMULBB( harm_Gain_Q15, B_Q14[ j ] ), 15 );\n        }\n        /* Gradually reduce excitation gain */\n        rand_scale_Q14 = SKP_RSHIFT( SKP_SMULBB( rand_scale_Q14, rand_Gain_Q15 ), 15 );\n\n        /* Slowly increase pitch lag */\n        psPLC->pitchL_Q8 += SKP_SMULWB( psPLC->pitchL_Q8, PITCH_DRIFT_FAC_Q16 );\n        psPLC->pitchL_Q8 = SKP_min_32( psPLC->pitchL_Q8, SKP_LSHIFT( SKP_SMULBB( MAX_PITCH_LAG_MS, psDec->fs_kHz ), 8 ) );\n        lag = SKP_RSHIFT_ROUND( psPLC->pitchL_Q8, 8 );\n    }\n\n    /***************************/\n    /* LPC synthesis filtering */\n    /***************************/\n    sig_Q10_ptr = sig_Q10;\n    /* Preload LPC coeficients to array on stack. Gives small performance gain */\n    SKP_memcpy( A_Q12_tmp.as_int16, psPLC->prevLPC_Q12, psDec->LPC_order * sizeof( SKP_int16 ) );\n    SKP_assert( psDec->LPC_order >= 10 ); /* check that unrolling works */\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        for( i = 0; i < psDec->subfr_length; i++ ){\n            /* partly unrolled */\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n            /* NOTE: the code below loads two int16 values in an int32, and multiplies each using the   */\n            /* SMLAWB and SMLAWT instructions. On a big-endian CPU the two int16 variables would be     */\n            /* loaded in reverse order and the code will give the wrong result. In that case swapping   */\n            /* the SMLAWB and SMLAWT instructions should solve the problem.                             */\n            Atmp = A_Q12_tmp.as_int32[ 0 ];    /* read two coefficients at once */\n            LPC_pred_Q10 = SKP_SMULWB(               psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  1 ], Atmp );\n            LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  2 ], Atmp );\n            Atmp = A_Q12_tmp.as_int32[ 1 ];\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  3 ], Atmp );\n            LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  4 ], Atmp );\n            Atmp = A_Q12_tmp.as_int32[ 2 ];\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  5 ], Atmp );\n            LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  6 ], Atmp );\n            Atmp = A_Q12_tmp.as_int32[ 3 ];\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  7 ], Atmp );\n            LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  8 ], Atmp );\n            Atmp = A_Q12_tmp.as_int32[ 4 ];\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  9 ], Atmp );\n            LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i - 10 ], Atmp );\n            for( j = 10 ; j < psDec->LPC_order ; j+=2 ) {\n                Atmp = A_Q12_tmp.as_int32[ j / 2 ];\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  1 - j ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  2 - j ], Atmp );\n            }\n#else\n            LPC_pred_Q10 = SKP_SMULWB(               psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  1 ], A_Q12_tmp.as_int16[ 0 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  2 ], A_Q12_tmp.as_int16[ 1 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  3 ], A_Q12_tmp.as_int16[ 2 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  4 ], A_Q12_tmp.as_int16[ 3 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  5 ], A_Q12_tmp.as_int16[ 4 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  6 ], A_Q12_tmp.as_int16[ 5 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  7 ], A_Q12_tmp.as_int16[ 6 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  8 ], A_Q12_tmp.as_int16[ 7 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i -  9 ], A_Q12_tmp.as_int16[ 8 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i - 10 ], A_Q12_tmp.as_int16[ 9 ] );\n\n            for( j = 10; j < psDec->LPC_order; j++ ) {\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, psDec->sLPC_Q14[ MAX_LPC_ORDER + i - j - 1 ], A_Q12_tmp.as_int16[ j ] );\n            }\n#endif\n            /* Add prediction to LPC residual */\n            sig_Q10_ptr[ i ] = SKP_ADD32( sig_Q10_ptr[ i ], LPC_pred_Q10 );\n                \n            /* Update states */\n            psDec->sLPC_Q14[ MAX_LPC_ORDER + i ] = SKP_LSHIFT( sig_Q10_ptr[ i ], 4 );\n        }\n        sig_Q10_ptr += psDec->subfr_length;\n        /* Update LPC filter state */\n        SKP_memcpy( psDec->sLPC_Q14, &psDec->sLPC_Q14[ psDec->subfr_length ], MAX_LPC_ORDER * sizeof( SKP_int32 ) );\n    }\n\n    /* Scale with Gain */\n    for( i = 0; i < psDec->frame_length; i++ ) {\n        signal[ i ] = ( SKP_int16 )SKP_SAT16( SKP_RSHIFT_ROUND( SKP_SMULWW( sig_Q10[ i ], psPLC->prevGain_Q16[ NB_SUBFR - 1 ] ), 10 ) );\n    }\n\n    /**************************************/\n    /* Update states                      */\n    /**************************************/\n    psPLC->rand_seed     = rand_seed;\n    psPLC->randScale_Q14 = rand_scale_Q14;\n    for( i = 0; i < NB_SUBFR; i++ ) {\n        psDecCtrl->pitchL[ i ] = lag;\n    }\n}\n\n/* Glues concealed frames with new good recieved frames             */\nvoid SKP_Silk_PLC_glue_frames(\n    SKP_Silk_decoder_state      *psDec,             /* I/O decoder state    */\n    SKP_Silk_decoder_control    *psDecCtrl,         /* I/O Decoder control  */\n    SKP_int16                   signal[],           /* I/O signal           */\n    SKP_int                     length              /* I length of residual */\n)\n{\n    SKP_int   i, energy_shift;\n    SKP_int32 energy;\n    SKP_Silk_PLC_struct *psPLC;\n    psPLC = &psDec->sPLC;\n\n    if( psDec->lossCnt ) {\n        /* Calculate energy in concealed residual */\n        SKP_Silk_sum_sqr_shift( &psPLC->conc_energy, &psPLC->conc_energy_shift, signal, length );\n        \n        psPLC->last_frame_lost = 1;\n    } else {\n        if( psDec->sPLC.last_frame_lost ) {\n            /* Calculate residual in decoded signal if last frame was lost */\n            SKP_Silk_sum_sqr_shift( &energy, &energy_shift, signal, length );\n\n            /* Normalize energies */\n            if( energy_shift > psPLC->conc_energy_shift ) {\n                psPLC->conc_energy = SKP_RSHIFT( psPLC->conc_energy, energy_shift - psPLC->conc_energy_shift );\n            } else if( energy_shift < psPLC->conc_energy_shift ) {\n                energy = SKP_RSHIFT( energy, psPLC->conc_energy_shift - energy_shift );\n            }\n\n            /* Fade in the energy difference */\n            if( energy > psPLC->conc_energy ) {\n                SKP_int32 frac_Q24, LZ;\n                SKP_int32 gain_Q12, slope_Q12;\n\n                LZ = SKP_Silk_CLZ32( psPLC->conc_energy );\n                LZ = LZ - 1;\n                psPLC->conc_energy = SKP_LSHIFT( psPLC->conc_energy, LZ );\n                energy = SKP_RSHIFT( energy, SKP_max_32( 24 - LZ, 0 ) );\n                \n                frac_Q24 = SKP_DIV32( psPLC->conc_energy, SKP_max( energy, 1 ) );\n                \n                gain_Q12 = SKP_Silk_SQRT_APPROX( frac_Q24 );\n                slope_Q12 = SKP_DIV32_16( ( 1 << 12 ) - gain_Q12, length );\n\n                for( i = 0; i < length; i++ ) {\n                    signal[ i ] = SKP_RSHIFT( SKP_MUL( gain_Q12, signal[ i ] ), 12 );\n                    gain_Q12 += slope_Q12;\n                    gain_Q12 = SKP_min( gain_Q12, ( 1 << 12 ) );\n                }\n            }\n        }\n        psPLC->last_frame_lost = 0;\n\n    }\n}\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_VAD.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*\n * File Name:   SKP_Silk_VAD.c\n * Description: Silk VAD.\n */\n\n#include <stdlib.h>\n#include \"SKP_Silk_main.h\"\n\n/**********************************/\n/* Initialization of the Silk VAD */\n/**********************************/\nSKP_int SKP_Silk_VAD_Init(                              /* O    Return value, 0 if success                  */ \n    SKP_Silk_VAD_state              *psSilk_VAD         /* I/O  Pointer to Silk VAD state                   */ \n)\n{\n    SKP_int b, ret = 0;\n\n    /* reset state memory */\n    SKP_memset( psSilk_VAD, 0, sizeof( SKP_Silk_VAD_state ) );\n\n    /* init noise levels */\n    /* Initialize array with approx pink noise levels (psd proportional to inverse of frequency) */\n    for( b = 0; b < VAD_N_BANDS; b++ ) {\n        psSilk_VAD->NoiseLevelBias[ b ] = SKP_max_32( SKP_DIV32_16( VAD_NOISE_LEVELS_BIAS, b + 1 ), 1 );\n    }\n\n    /* Initialize state */\n    for( b = 0; b < VAD_N_BANDS; b++ ) {\n        psSilk_VAD->NL[ b ]     = SKP_MUL( 100, psSilk_VAD->NoiseLevelBias[ b ] );\n        psSilk_VAD->inv_NL[ b ] = SKP_DIV32( SKP_int32_MAX, psSilk_VAD->NL[ b ] );\n    }\n    psSilk_VAD->counter = 15;\n\n    /* init smoothed energy-to-noise ratio*/\n    for( b = 0; b < VAD_N_BANDS; b++ ) {\n        psSilk_VAD->NrgRatioSmth_Q8[ b ] = 100 * 256;       /* 100 * 256 --> 20 dB SNR */\n    }\n\n    return( ret );\n}\n\n/* Weighting factors for tilt measure */\nconst static SKP_int32 tiltWeights[ VAD_N_BANDS ] = { 30000, 6000, -12000, -12000 };\n\n/***************************************/\n/* Get the speech activity level in Q8 */\n/***************************************/\nSKP_int SKP_Silk_VAD_GetSA_Q8(                                      /* O    Return value, 0 if success      */\n    SKP_Silk_VAD_state              *psSilk_VAD,                    /* I/O  Silk VAD state                  */\n    SKP_int                         *pSA_Q8,                        /* O    Speech activity level in Q8     */\n    SKP_int                         *pSNR_dB_Q7,                    /* O    SNR for current frame in Q7     */\n    SKP_int                         pQuality_Q15[ VAD_N_BANDS ],    /* O    Smoothed SNR for each band      */\n    SKP_int                         *pTilt_Q15,                     /* O    current frame's frequency tilt  */\n    const SKP_int16                 pIn[],                          /* I    PCM input       [framelength]   */\n    const SKP_int                   framelength                     /* I    Input frame length              */\n)\n{\n    SKP_int   SA_Q15, input_tilt;\n    SKP_int32 scratch[ 3 * MAX_FRAME_LENGTH / 2 ];\n    SKP_int   decimated_framelength, dec_subframe_length, dec_subframe_offset, SNR_Q7, i, b, s;\n    SKP_int32 sumSquared, smooth_coef_Q16;\n    SKP_int16 HPstateTmp;\n\n    SKP_int16 X[ VAD_N_BANDS ][ MAX_FRAME_LENGTH / 2 ];\n    SKP_int32 Xnrg[ VAD_N_BANDS ];\n    SKP_int32 NrgToNoiseRatio_Q8[ VAD_N_BANDS ];\n    SKP_int32 speech_nrg, x_tmp;\n    SKP_int   ret = 0;\n\n    /* Safety checks */\n    SKP_assert( VAD_N_BANDS == 4 );\n    SKP_assert( MAX_FRAME_LENGTH >= framelength );\n    SKP_assert( framelength <= 512 );\n\n    /***********************/\n    /* Filter and Decimate */\n    /***********************/\n    /* 0-8 kHz to 0-4 kHz and 4-8 kHz */\n    SKP_Silk_ana_filt_bank_1( pIn,          &psSilk_VAD->AnaState[  0 ], &X[ 0 ][ 0 ], &X[ 3 ][ 0 ], &scratch[ 0 ], framelength );        \n    \n    /* 0-4 kHz to 0-2 kHz and 2-4 kHz */\n    SKP_Silk_ana_filt_bank_1( &X[ 0 ][ 0 ], &psSilk_VAD->AnaState1[ 0 ], &X[ 0 ][ 0 ], &X[ 2 ][ 0 ], &scratch[ 0 ], SKP_RSHIFT( framelength, 1 ) );\n    \n    /* 0-2 kHz to 0-1 kHz and 1-2 kHz */\n    SKP_Silk_ana_filt_bank_1( &X[ 0 ][ 0 ], &psSilk_VAD->AnaState2[ 0 ], &X[ 0 ][ 0 ], &X[ 1 ][ 0 ], &scratch[ 0 ], SKP_RSHIFT( framelength, 2 ) );\n\n    /*********************************************/\n    /* HP filter on lowest band (differentiator) */\n    /*********************************************/\n    decimated_framelength = SKP_RSHIFT( framelength, 3 );\n    X[ 0 ][ decimated_framelength - 1 ] = SKP_RSHIFT( X[ 0 ][ decimated_framelength - 1 ], 1 );\n    HPstateTmp = X[ 0 ][ decimated_framelength - 1 ];\n    for( i = decimated_framelength - 1; i > 0; i-- ) {\n        X[ 0 ][ i - 1 ]  = SKP_RSHIFT( X[ 0 ][ i - 1 ], 1 );\n        X[ 0 ][ i ]     -= X[ 0 ][ i - 1 ];\n    }\n    X[ 0 ][ 0 ] -= psSilk_VAD->HPstate;\n    psSilk_VAD->HPstate = HPstateTmp;\n\n    /*************************************/\n    /* Calculate the energy in each band */\n    /*************************************/\n    for( b = 0; b < VAD_N_BANDS; b++ ) {        \n        /* Find the decimated framelength in the non-uniformly divided bands */\n        decimated_framelength = SKP_RSHIFT( framelength, SKP_min_int( VAD_N_BANDS - b, VAD_N_BANDS - 1 ) );\n\n        /* Split length into subframe lengths */\n        dec_subframe_length = SKP_RSHIFT( decimated_framelength, VAD_INTERNAL_SUBFRAMES_LOG2 );\n        dec_subframe_offset = 0;\n\n        /* Compute energy per sub-frame */\n        /* initialize with summed energy of last subframe */\n        Xnrg[ b ] = psSilk_VAD->XnrgSubfr[ b ];\n        for( s = 0; s < VAD_INTERNAL_SUBFRAMES; s++ ) {\n            sumSquared = 0;\n            for( i = 0; i < dec_subframe_length; i++ ) {\n                /* The energy will be less than dec_subframe_length * ( SKP_int16_MIN / 8 ) ^ 2.            */\n                /* Therefore we can accumulate with no risk of overflow (unless dec_subframe_length > 128)  */\n                x_tmp = SKP_RSHIFT( X[ b ][ i + dec_subframe_offset ], 3 );\n                sumSquared = SKP_SMLABB( sumSquared, x_tmp, x_tmp );\n\n                /* Safety check */\n                SKP_assert( sumSquared >= 0 );\n            }\n\n            /* Add/saturate summed energy of current subframe */\n            if( s < VAD_INTERNAL_SUBFRAMES - 1 ) {\n                Xnrg[ b ] = SKP_ADD_POS_SAT32( Xnrg[ b ], sumSquared );\n            } else {\n                /* Look-ahead subframe */\n                Xnrg[ b ] = SKP_ADD_POS_SAT32( Xnrg[ b ], SKP_RSHIFT( sumSquared, 1 ) );\n            }\n\n            dec_subframe_offset += dec_subframe_length;\n        }\n        psSilk_VAD->XnrgSubfr[ b ] = sumSquared; \n    }\n\n    /********************/\n    /* Noise estimation */\n    /********************/\n    SKP_Silk_VAD_GetNoiseLevels( &Xnrg[ 0 ], psSilk_VAD );\n\n    /***********************************************/\n    /* Signal-plus-noise to noise ratio estimation */\n    /***********************************************/\n    sumSquared = 0;\n    input_tilt = 0;\n    for( b = 0; b < VAD_N_BANDS; b++ ) {\n        speech_nrg = Xnrg[ b ] - psSilk_VAD->NL[ b ];\n        if( speech_nrg > 0 ) {\n            /* Divide, with sufficient resolution */\n            if( ( Xnrg[ b ] & 0xFF800000 ) == 0 ) {\n                NrgToNoiseRatio_Q8[ b ] = SKP_DIV32( SKP_LSHIFT( Xnrg[ b ], 8 ), psSilk_VAD->NL[ b ] + 1 );\n            } else {\n                NrgToNoiseRatio_Q8[ b ] = SKP_DIV32( Xnrg[ b ], SKP_RSHIFT( psSilk_VAD->NL[ b ], 8 ) + 1 );\n            }\n\n            /* Convert to log domain */\n            SNR_Q7 = SKP_Silk_lin2log( NrgToNoiseRatio_Q8[ b ] ) - 8 * 128;\n\n            /* Sum-of-squares */\n            sumSquared = SKP_SMLABB( sumSquared, SNR_Q7, SNR_Q7 );          /* Q14 */\n\n            /* Tilt measure */\n            if( speech_nrg < ( 1 << 20 ) ) {\n                /* Scale down SNR value for small subband speech energies */\n                SNR_Q7 = SKP_SMULWB( SKP_LSHIFT( SKP_Silk_SQRT_APPROX( speech_nrg ), 6 ), SNR_Q7 );\n            }\n            input_tilt = SKP_SMLAWB( input_tilt, tiltWeights[ b ], SNR_Q7 );\n        } else {\n            NrgToNoiseRatio_Q8[ b ] = 256;\n        }\n    }\n\n    /* Mean-of-squares */\n    sumSquared = SKP_DIV32_16( sumSquared, VAD_N_BANDS ); /* Q14 */\n\n    /* Root-mean-square approximation, scale to dBs, and write to output pointer */\n    *pSNR_dB_Q7 = ( SKP_int16 )( 3 * SKP_Silk_SQRT_APPROX( sumSquared ) );  /* Q7 */\n\n    /*********************************/\n    /* Speech Probability Estimation */\n    /*********************************/\n    SA_Q15 = SKP_Silk_sigm_Q15( SKP_SMULWB( VAD_SNR_FACTOR_Q16, *pSNR_dB_Q7 ) - VAD_NEGATIVE_OFFSET_Q5 );\n\n    /**************************/\n    /* Frequency Tilt Measure */\n    /**************************/\n    *pTilt_Q15 = SKP_LSHIFT( SKP_Silk_sigm_Q15( input_tilt ) - 16384, 1 );\n\n    /**************************************************/\n    /* Scale the sigmoid output based on power levels */\n    /**************************************************/\n    speech_nrg = 0;\n    for( b = 0; b < VAD_N_BANDS; b++ ) {\n        /* Accumulate signal-without-noise energies, higher frequency bands have more weight */\n        speech_nrg += ( b + 1 ) * SKP_RSHIFT( Xnrg[ b ] - psSilk_VAD->NL[ b ], 4 );\n    }\n\n    /* Power scaling */\n    if( speech_nrg <= 0 ) {\n        SA_Q15 = SKP_RSHIFT( SA_Q15, 1 ); \n    } else if( speech_nrg < 32768 ) {\n        /* square-root */\n        speech_nrg = SKP_Silk_SQRT_APPROX( SKP_LSHIFT( speech_nrg, 15 ) );\n        SA_Q15 = SKP_SMULWB( 32768 + speech_nrg, SA_Q15 ); \n    }\n\n    /* Copy the resulting speech activity in Q8 to *pSA_Q8 */\n    *pSA_Q8 = SKP_min_int( SKP_RSHIFT( SA_Q15, 7 ), SKP_uint8_MAX );\n\n    /***********************************/\n    /* Energy Level and SNR estimation */\n    /***********************************/\n    /* Smoothing coefficient */\n    smooth_coef_Q16 = SKP_SMULWB( VAD_SNR_SMOOTH_COEF_Q18, SKP_SMULWB( SA_Q15, SA_Q15 ) );\n    for( b = 0; b < VAD_N_BANDS; b++ ) {\n        /* compute smoothed energy-to-noise ratio per band */\n        psSilk_VAD->NrgRatioSmth_Q8[ b ] = SKP_SMLAWB( psSilk_VAD->NrgRatioSmth_Q8[ b ], \n            NrgToNoiseRatio_Q8[ b ] - psSilk_VAD->NrgRatioSmth_Q8[ b ], smooth_coef_Q16 );\n\n        /* signal to noise ratio in dB per band */\n        SNR_Q7 = 3 * ( SKP_Silk_lin2log( psSilk_VAD->NrgRatioSmth_Q8[b] ) - 8 * 128 );\n        /* quality = sigmoid( 0.25 * ( SNR_dB - 16 ) ); */\n        pQuality_Q15[ b ] = SKP_Silk_sigm_Q15( SKP_RSHIFT( SNR_Q7 - 16 * 128, 4 ) );\n    }\n\n    return( ret );\n}\n\n/**************************/\n/* Noise level estimation */\n/**************************/\nvoid SKP_Silk_VAD_GetNoiseLevels(\n    const SKP_int32                 pX[ VAD_N_BANDS ],  /* I    subband energies                            */\n    SKP_Silk_VAD_state              *psSilk_VAD         /* I/O  Pointer to Silk VAD state                   */ \n)\n{\n    SKP_int   k;\n    SKP_int32 nl, nrg, inv_nrg;\n    SKP_int   coef, min_coef;\n\n    /* Initially faster smoothing */\n    if( psSilk_VAD->counter < 1000 ) { /* 1000 = 20 sec */\n        min_coef = SKP_DIV32_16( SKP_int16_MAX, SKP_RSHIFT( psSilk_VAD->counter, 4 ) + 1 );  \n    } else {\n        min_coef = 0;\n    }\n\n    for( k = 0; k < VAD_N_BANDS; k++ ) {\n        /* Get old noise level estimate for current band */\n        nl = psSilk_VAD->NL[ k ];\n        SKP_assert( nl >= 0 );\n        \n        /* Add bias */\n        nrg = SKP_ADD_POS_SAT32( pX[ k ], psSilk_VAD->NoiseLevelBias[ k ] ); \n        SKP_assert( nrg > 0 );\n        \n        /* Invert energies */\n        inv_nrg = SKP_DIV32( SKP_int32_MAX, nrg );\n        SKP_assert( inv_nrg >= 0 );\n        \n        /* Less update when subband energy is high */\n        if( nrg > SKP_LSHIFT( nl, 3 ) ) {\n            coef = VAD_NOISE_LEVEL_SMOOTH_COEF_Q16 >> 3;\n        } else if( nrg < nl ) {\n            coef = VAD_NOISE_LEVEL_SMOOTH_COEF_Q16;\n        } else {\n            coef = SKP_SMULWB( SKP_SMULWW( inv_nrg, nl ), VAD_NOISE_LEVEL_SMOOTH_COEF_Q16 << 1 );\n        }\n\n        /* Initially faster smoothing */\n        coef = SKP_max_int( coef, min_coef );\n\n        /* Smooth inverse energies */\n        psSilk_VAD->inv_NL[ k ] = SKP_SMLAWB( psSilk_VAD->inv_NL[ k ], inv_nrg - psSilk_VAD->inv_NL[ k ], coef );\n        SKP_assert( psSilk_VAD->inv_NL[ k ] >= 0 );\n\n        /* Compute noise level by inverting again */\n        nl = SKP_DIV32( SKP_int32_MAX, psSilk_VAD->inv_NL[ k ] );\n        SKP_assert( nl >= 0 );\n\n        /* Limit noise levels (guarantee 7 bits of head room) */\n        nl = SKP_min( nl, 0x00FFFFFF );\n\n        /* Store as part of state */\n        psSilk_VAD->NL[ k ] = nl;\n    }\n\n    /* Increment frame counter */\n    psSilk_VAD->counter++;\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_VQ_nearest_neighbor_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\n/* Entropy constrained MATRIX-weighted VQ, hard-coded to 5-element vectors, for a single input data vector */\nvoid SKP_Silk_VQ_WMat_EC_FIX(\n    SKP_int                         *ind,               /* O    index of best codebook vector               */\n    SKP_int32                       *rate_dist_Q14,     /* O    best weighted quantization error + mu * rate*/\n    const SKP_int16                 *in_Q14,            /* I    input vector to be quantized                */\n    const SKP_int32                 *W_Q18,             /* I    weighting matrix                            */\n    const SKP_int16                 *cb_Q14,            /* I    codebook                                    */\n    const SKP_int16                 *cl_Q6,             /* I    code length for each codebook vector        */\n    const SKP_int                   mu_Q8,              /* I    tradeoff between weighted error and rate    */\n    SKP_int                         L                   /* I    number of vectors in codebook               */\n)\n{\n    SKP_int   k;\n    const SKP_int16 *cb_row_Q14;\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n    SKP_int32 sum1_Q14, sum2_Q16, diff_Q14_01, diff_Q14_23, diff_Q14_4;\n#else\n    SKP_int16 diff_Q14[ 5 ];\n    SKP_int32 sum1_Q14, sum2_Q16;\n#endif\n\n    /* Loop over codebook */\n    *rate_dist_Q14 = SKP_int32_MAX;\n    cb_row_Q14 = cb_Q14;\n    for( k = 0; k < L; k++ ) {\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n        /* Pack pairs of int16 values per int32 */\n        diff_Q14_01 = ( SKP_uint16 )( in_Q14[ 0 ] - cb_row_Q14[ 0 ] ) | SKP_LSHIFT( ( SKP_int32 )in_Q14[ 1 ] - cb_row_Q14[ 1 ], 16 );\n        diff_Q14_23 = ( SKP_uint16 )( in_Q14[ 2 ] - cb_row_Q14[ 2 ] ) | SKP_LSHIFT( ( SKP_int32 )in_Q14[ 3 ] - cb_row_Q14[ 3 ], 16 );\n        diff_Q14_4  = in_Q14[ 4 ] - cb_row_Q14[ 4 ];\n#else\n        diff_Q14[ 0 ] = in_Q14[ 0 ] - cb_row_Q14[ 0 ];\n        diff_Q14[ 1 ] = in_Q14[ 1 ] - cb_row_Q14[ 1 ];\n        diff_Q14[ 2 ] = in_Q14[ 2 ] - cb_row_Q14[ 2 ];\n        diff_Q14[ 3 ] = in_Q14[ 3 ] - cb_row_Q14[ 3 ];\n        diff_Q14[ 4 ] = in_Q14[ 4 ] - cb_row_Q14[ 4 ];\n#endif\n\n        /* Weighted rate */\n        sum1_Q14 = SKP_SMULBB( mu_Q8, cl_Q6[ k ] );\n\n        SKP_assert( sum1_Q14 >= 0 );\n\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n        /* Add weighted quantization error, assuming W_Q18 is symmetric */\n        /* NOTE: the code below loads two int16 values as one int32, and multiplies each using the  */\n        /* SMLAWB and SMLAWT instructions. On a big-endian CPU the two int16 variables would be     */\n        /* loaded in reverse order and the code will give the wrong result. In that case swapping   */\n        /* the SMLAWB and SMLAWT instructions should solve the problem.                             */\n        /* first row of W_Q18 */\n        sum2_Q16 = SKP_SMULWT(           W_Q18[ 1 ], diff_Q14_01 );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[ 2 ], diff_Q14_23 );\n        sum2_Q16 = SKP_SMLAWT( sum2_Q16, W_Q18[ 3 ], diff_Q14_23 );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[ 4 ], diff_Q14_4  );\n        sum2_Q16 = SKP_LSHIFT( sum2_Q16, 1 );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[ 0 ], diff_Q14_01 );\n        sum1_Q14 = SKP_SMLAWB( sum1_Q14, sum2_Q16,   diff_Q14_01 );\n\n        /* second row of W_Q18 */\n        sum2_Q16 = SKP_SMULWB(           W_Q18[ 7 ], diff_Q14_23 );\n        sum2_Q16 = SKP_SMLAWT( sum2_Q16, W_Q18[ 8 ], diff_Q14_23 );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[ 9 ], diff_Q14_4  );\n        sum2_Q16 = SKP_LSHIFT( sum2_Q16, 1 );\n        sum2_Q16 = SKP_SMLAWT( sum2_Q16, W_Q18[ 6 ], diff_Q14_01 );\n        sum1_Q14 = SKP_SMLAWT( sum1_Q14, sum2_Q16,   diff_Q14_01 );\n\n        /* third row of W_Q18 */\n        sum2_Q16 = SKP_SMULWT(           W_Q18[ 13 ], diff_Q14_23 );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[ 14 ], diff_Q14_4  );\n        sum2_Q16 = SKP_LSHIFT( sum2_Q16, 1 );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[ 12 ], diff_Q14_23 );\n        sum1_Q14 = SKP_SMLAWB( sum1_Q14, sum2_Q16,    diff_Q14_23 );\n\n        /* fourth row of W_Q18 */\n        sum2_Q16 = SKP_SMULWB(           W_Q18[ 19 ], diff_Q14_4  );\n        sum2_Q16 = SKP_LSHIFT( sum2_Q16, 1 );\n        sum2_Q16 = SKP_SMLAWT( sum2_Q16, W_Q18[ 18 ], diff_Q14_23 );\n        sum1_Q14 = SKP_SMLAWT( sum1_Q14, sum2_Q16,    diff_Q14_23 );\n\n        /* last row of W_Q18 */\n        sum2_Q16 = SKP_SMULWB(           W_Q18[ 24 ], diff_Q14_4  );\n        sum1_Q14 = SKP_SMLAWB( sum1_Q14, sum2_Q16,    diff_Q14_4  );\n#else\n        /* first row of W_Q18 */\n        sum2_Q16 = SKP_SMULWB(           W_Q18[  1 ], diff_Q14[ 1 ] );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[  2 ], diff_Q14[ 2 ] );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[  3 ], diff_Q14[ 3 ] );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[  4 ], diff_Q14[ 4 ] );\n        sum2_Q16 = SKP_LSHIFT( sum2_Q16, 1 );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[  0 ], diff_Q14[ 0 ] );\n        sum1_Q14 = SKP_SMLAWB( sum1_Q14, sum2_Q16,    diff_Q14[ 0 ] );\n\n        /* second row of W_Q18 */\n        sum2_Q16 = SKP_SMULWB(           W_Q18[  7 ], diff_Q14[ 2 ] ); \n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[  8 ], diff_Q14[ 3 ] );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[  9 ], diff_Q14[ 4 ] );\n        sum2_Q16 = SKP_LSHIFT( sum2_Q16, 1 );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[  6 ], diff_Q14[ 1 ] );\n        sum1_Q14 = SKP_SMLAWB( sum1_Q14, sum2_Q16,    diff_Q14[ 1 ] );\n\n        /* third row of W_Q18 */\n        sum2_Q16 = SKP_SMULWB(           W_Q18[ 13 ], diff_Q14[ 3 ] ); \n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[ 14 ], diff_Q14[ 4 ] );\n        sum2_Q16 = SKP_LSHIFT( sum2_Q16, 1 );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[ 12 ], diff_Q14[ 2 ] );\n        sum1_Q14 = SKP_SMLAWB( sum1_Q14, sum2_Q16,    diff_Q14[ 2 ] );\n\n        /* fourth row of W_Q18 */\n        sum2_Q16 = SKP_SMULWB(           W_Q18[ 19 ], diff_Q14[ 4 ] ); \n        sum2_Q16 = SKP_LSHIFT( sum2_Q16, 1 );\n        sum2_Q16 = SKP_SMLAWB( sum2_Q16, W_Q18[ 18 ], diff_Q14[ 3 ] );\n        sum1_Q14 = SKP_SMLAWB( sum1_Q14, sum2_Q16,    diff_Q14[ 3 ] );\n\n        /* last row of W_Q18 */\n        sum2_Q16 = SKP_SMULWB(           W_Q18[ 24 ], diff_Q14[ 4 ] ); \n        sum1_Q14 = SKP_SMLAWB( sum1_Q14, sum2_Q16,    diff_Q14[ 4 ] );\n#endif\n\n        SKP_assert( sum1_Q14 >= 0 );\n\n        /* find best */\n        if( sum1_Q14 < *rate_dist_Q14 ) {\n            *rate_dist_Q14 = sum1_Q14;\n            *ind = k;\n        }\n\n        /* Go to next cbk vector */\n        cb_row_Q14 += LTP_ORDER;\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_ana_filt_bank_1.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                          *\n * SKP_ana_filt_bank_1.c                                                    *\n *                                                                          *\n * Split signal into two decimated bands using first-order allpass filters  *\n *                                                                          *\n * Copyright 2006 (c), Skype Limited                                        *\n * Date: 060221                                                             *\n *                                                                          */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n#if EMBEDDED_ARM<5\n/* Coefficients for 2-band filter bank based on first-order allpass filters */\n// old\nstatic SKP_int16 A_fb1_20[ 1 ] = {  5394 << 1 };\nstatic SKP_int16 A_fb1_21[ 1 ] = { 20623 << 1 };        /* wrap-around to negative number is intentional */\n\n/* Split signal into two decimated bands using first-order allpass filters */\nvoid SKP_Silk_ana_filt_bank_1(\n    const SKP_int16      *in,        /* I:   Input signal [N]        */\n    SKP_int32            *S,         /* I/O: State vector [2]        */\n    SKP_int16            *outL,      /* O:   Low band [N/2]          */\n    SKP_int16            *outH,      /* O:   High band [N/2]         */\n    SKP_int32            *scratch,   /* I:   Scratch memory [3*N/2]  */   // todo: remove - no longer used\n    const SKP_int32      N           /* I:   Number of input samples */\n)\n{\n    SKP_int      k, N2 = SKP_RSHIFT( N, 1 );\n    SKP_int32    in32, X, Y, out_1, out_2;\n\n    /* Internal variables and state are in Q10 format */\n    for( k = 0; k < N2; k++ ) {\n        /* Convert to Q10 */\n        in32 = SKP_LSHIFT( (SKP_int32)in[ 2 * k ], 10 );\n\n        /* All-pass section for even input sample */\n        Y      = SKP_SUB32( in32, S[ 0 ] );\n        X      = SKP_SMLAWB( Y, Y, A_fb1_21[ 0 ] );\n        out_1  = SKP_ADD32( S[ 0 ], X );\n        S[ 0 ] = SKP_ADD32( in32, X );\n\n        /* Convert to Q10 */\n        in32 = SKP_LSHIFT( (SKP_int32)in[ 2 * k + 1 ], 10 );\n\n        /* All-pass section for odd input sample */\n        Y      = SKP_SUB32( in32, S[ 1 ] );\n        X      = SKP_SMULWB( Y, A_fb1_20[ 0 ] );\n        out_2  = SKP_ADD32( S[ 1 ], X );\n        S[ 1 ] = SKP_ADD32( in32, X );\n\n        /* Add/subtract, convert back to int16 and store to output */\n        outL[ k ] = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( SKP_ADD32( out_2, out_1 ), 11 ) );\n        outH[ k ] = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( SKP_SUB32( out_2, out_1 ), 11 ) );\n    }\n}\n#endif\n"
  },
  {
    "path": "app/jni/SKP_Silk_apply_sine_window.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Apply sine window to signal vector.                                      */\n/* Window types:                                                            */\n/*    1 -> sine window from 0 to pi/2                                       */\n/*    2 -> sine window from pi/2 to pi                                      */\n/* Every other sample is linearly interpolated, for speed.                  */\n/* Window length must be between 16 and 120 (incl) and a multiple of 4.     */\n\n/* Matlab code for table: \n   for k=16:9*4:16+2*9*4, fprintf(' %7.d,', -round(65536*pi ./ (k:4:k+8*4))); fprintf('\\n'); end\n*/\nstatic SKP_int16 freq_table_Q16[ 27 ] = {\n   12111,    9804,    8235,    7100,    6239,    5565,    5022,    4575,    4202,\n    3885,    3612,    3375,    3167,    2984,    2820,    2674,    2542,    2422,\n    2313,    2214,    2123,    2038,    1961,    1889,    1822,    1760,    1702,\n};\n\n//#if EMBEDDED_ARM<6\nvoid SKP_Silk_apply_sine_window(\n    SKP_int16                        px_win[],            /* O    Pointer to windowed signal                  */\n    const SKP_int16                  px[],                /* I    Pointer to input signal                     */\n    const SKP_int                    win_type,            /* I    Selects a window type                       */\n    const SKP_int                    length               /* I    Window length, multiple of 4                */\n)\n{\n    SKP_int   k, f_Q16, c_Q16;\n    SKP_int32 S0_Q16, S1_Q16;\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n    SKP_int32 px32;\n#endif\n    SKP_assert( win_type == 1 || win_type == 2 );\n\n    /* Length must be in a range from 16 to 120 and a multiple of 4 */\n    SKP_assert( length >= 16 && length <= 120 );\n    SKP_assert( ( length & 3 ) == 0 );\n\n    /* Input pointer must be 4-byte aligned */\n    SKP_assert( ( ( SKP_int64 )( ( SKP_int8* )px - ( SKP_int8* )0 ) & 3 ) == 0 );\n\n    /* Frequency */\n    k = ( length >> 2 ) - 4;\n    SKP_assert( k >= 0 && k <= 26 );\n    f_Q16 = (SKP_int)freq_table_Q16[ k ];\n\n    /* Factor used for cosine approximation */\n    c_Q16 = SKP_SMULWB( f_Q16, -f_Q16 );\n    SKP_assert( c_Q16 >= -32768 );\n\n    /* initialize state */\n    if( win_type == 1 ) {\n        /* start from 0 */\n        S0_Q16 = 0;\n        /* approximation of sin(f) */\n        S1_Q16 = f_Q16 + SKP_RSHIFT( length, 3 );\n    } else {\n        /* start from 1 */\n        S0_Q16 = ( 1 << 16 );\n        /* approximation of cos(f) */\n        S1_Q16 = ( 1 << 16 ) + SKP_RSHIFT( c_Q16, 1 ) + SKP_RSHIFT( length, 4 );\n    }\n\n    /* Uses the recursive equation:   sin(n*f) = 2 * cos(f) * sin((n-1)*f) - sin((n-2)*f)    */\n    /* 4 samples at a time */\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n    for( k = 0; k < length; k += 4 ) {\n        px32 = *( (SKP_int32 *)&px[ k ] );                        /* load two values at once */\n        px_win[ k ]     = (SKP_int16)SKP_SMULWB( SKP_RSHIFT( S0_Q16 + S1_Q16, 1 ), px32 );\n        px_win[ k + 1 ] = (SKP_int16)SKP_SMULWT( S1_Q16, px32 );\n        S0_Q16 = SKP_SMULWB( S1_Q16, c_Q16 ) + SKP_LSHIFT( S1_Q16, 1 ) - S0_Q16 + 1;\n        S0_Q16 = SKP_min( S0_Q16, ( 1 << 16 ) );\n\n        px32 = *( (SKP_int32 *)&px[k + 2] );                      /* load two values at once */\n        px_win[ k + 2 ] = (SKP_int16)SKP_SMULWB( SKP_RSHIFT( S0_Q16 + S1_Q16, 1 ), px32 );\n        px_win[ k + 3 ] = (SKP_int16)SKP_SMULWT( S0_Q16, px32 );\n        S1_Q16 = SKP_SMULWB( S0_Q16, c_Q16 ) + SKP_LSHIFT( S0_Q16, 1 ) - S1_Q16;\n        S1_Q16 = SKP_min( S1_Q16, ( 1 << 16 ) );\n    }\n#else\n    for( k = 0; k < length; k += 4 ) {\n        px_win[ k ]     = (SKP_int16)SKP_SMULWB( SKP_RSHIFT( S0_Q16 + S1_Q16, 1 ), px[ k ] );\n        px_win[ k + 1 ] = (SKP_int16)SKP_SMULWB( S1_Q16, px[ k + 1] );\n        S0_Q16 = SKP_SMULWB( S1_Q16, c_Q16 ) + SKP_LSHIFT( S1_Q16, 1 ) - S0_Q16 + 1;\n        S0_Q16 = SKP_min( S0_Q16, ( 1 << 16 ) );\n\n        px_win[ k + 2 ] = (SKP_int16)SKP_SMULWB( SKP_RSHIFT( S0_Q16 + S1_Q16, 1 ), px[ k + 2] );\n        px_win[ k + 3 ] = (SKP_int16)SKP_SMULWB( S0_Q16, px[ k + 3 ] );\n        S1_Q16 = SKP_SMULWB( S0_Q16, c_Q16 ) + SKP_LSHIFT( S0_Q16, 1 ) - S1_Q16;\n        S1_Q16 = SKP_min( S1_Q16, ( 1 << 16 ) );\n    }\n#endif\n}\n//#endif\n"
  },
  {
    "path": "app/jni/SKP_Silk_array_maxabs.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_int16_array_maxabs.c                                      *\n *                                                                      *\n * Function that returns the maximum absolut value of                   *\n * the input vector                                                     *\n *                                                                      *\n * Copyright 2006 (c), Skype Limited                                    *\n * Date: 060221                                                         *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Function that returns the maximum absolut value of the input vector */\n#if (EMBEDDED_ARM<4)  \nSKP_int16 SKP_Silk_int16_array_maxabs(    /* O    Maximum absolute value, max: 2^15-1   */\n    const SKP_int16        *vec,            /* I    Input vector  [len]                   */\n    const SKP_int32        len              /* I    Length of input vector                */\n)                    \n{\n    SKP_int32 max = 0, i, lvl = 0, ind;\n\tif( len == 0 ) return 0;\n\n    ind = len - 1;\n    max = SKP_SMULBB( vec[ ind ], vec[ ind ] );\n    for( i = len - 2; i >= 0; i-- ) {\n        lvl = SKP_SMULBB( vec[ i ], vec[ i ] );\n        if( lvl > max ) {\n            max = lvl;\n            ind = i;\n        }\n    }\n\n    /* Do not return 32768, as it will not fit in an int16 so may lead to problems later on */\n    if( max >= 1073676289 ) { // (2^15-1)^2 = 1073676289\n        return( SKP_int16_MAX );\n    } else {\n        if( vec[ ind ] < 0 ) {\n            return( -vec[ ind ] );\n        } else {\n            return(  vec[ ind ] );\n        }\n    }\n}\n#endif\n"
  },
  {
    "path": "app/jni/SKP_Silk_autocorr.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_autocorr.c                                                *\n *                                                                      *\n * Calculates the autocorrelation                                       *\n * The result has 29 non-zero bits for the first correlation, to leave  *\n * some    room for adding white noise fractions etc.                   *\n *                                                                      *\n * Copyright 2008 (c), Skype Limited                                    *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Compute autocorrelation */\nvoid SKP_Silk_autocorr( \n    SKP_int32        *results,                   /* O    Result (length correlationCount)            */\n    SKP_int          *scale,                     /* O    Scaling of the correlation vector           */\n    const SKP_int16  *inputData,                 /* I    Input data to correlate                     */\n    const SKP_int    inputDataSize,              /* I    Length of input                             */\n    const SKP_int    correlationCount            /* I    Number of correlation taps to compute       */\n)\n{\n    SKP_int   i, lz, nRightShifts, corrCount;\n    SKP_int64 corr64;\n\n    corrCount = SKP_min_int( inputDataSize, correlationCount );\n\n    /* compute energy (zero-lag correlation) */\n    corr64 = SKP_Silk_inner_prod16_aligned_64( inputData, inputData, inputDataSize );\n\n    /* deal with all-zero input data */\n    corr64 += 1;\n\n    /* number of leading zeros */\n    lz = SKP_Silk_CLZ64( corr64 );\n\n    /* scaling: number of right shifts applied to correlations */\n    nRightShifts = 35 - lz;\n    *scale = nRightShifts;\n\n    if( nRightShifts <= 0 ) {\n        results[ 0 ] = SKP_LSHIFT( (SKP_int32)SKP_CHECK_FIT32( corr64 ), -nRightShifts );\n\n        /* compute remaining correlations based on int32 inner product */\n          for( i = 1; i < corrCount; i++ ) {\n            results[ i ] = SKP_LSHIFT( SKP_Silk_inner_prod_aligned( inputData, inputData + i, inputDataSize - i ), -nRightShifts );\n        }\n    } else {\n        results[ 0 ] = (SKP_int32)SKP_CHECK_FIT32( SKP_RSHIFT64( corr64, nRightShifts ) );\n\n        /* compute remaining correlations based on int64 inner product */\n          for( i = 1; i < corrCount; i++ ) {\n            results[ i ] =  (SKP_int32)SKP_CHECK_FIT32( SKP_RSHIFT64( SKP_Silk_inner_prod16_aligned_64( inputData, inputData + i, inputDataSize - i ), nRightShifts ) );\n        }\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_biquad.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_biquad.c                                                  *\n *                                                                      *\n * Second order ARMA filter                                             *\n * Can handle slowly varying filter coefficients                        *\n *                                                                      *\n * Copyright 2006 (c), Skype Limited                                    *\n * Date: 060221                                                         *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Second order ARMA filter */\n/* Can handle slowly varying filter coefficients */\nvoid SKP_Silk_biquad(\n    const SKP_int16      *in,        /* I:    input signal               */\n    const SKP_int16      *B,         /* I:    MA coefficients, Q13 [3]   */\n    const SKP_int16      *A,         /* I:    AR coefficients, Q13 [2]   */\n    SKP_int32            *S,         /* I/O:  state vector [2]           */\n    SKP_int16            *out,       /* O:    output signal              */\n    const SKP_int32      len         /* I:    signal length              */\n)\n{\n    SKP_int   k, in16;\n    SKP_int32 A0_neg, A1_neg, S0, S1, out32, tmp32;\n\n    S0 = S[ 0 ];\n    S1 = S[ 1 ];\n    A0_neg = -A[ 0 ];\n    A1_neg = -A[ 1 ];\n    for( k = 0; k < len; k++ ) {\n        /* S[ 0 ], S[ 1 ]: Q13 */\n        in16  = in[ k ];\n        out32 = SKP_SMLABB( S0, in16, B[ 0 ] );\n\n        S0 = SKP_SMLABB( S1, in16, B[ 1 ] );\n        S0 += SKP_LSHIFT( SKP_SMULWB( out32, A0_neg ), 3 );\n\n        S1 = SKP_LSHIFT( SKP_SMULWB( out32, A1_neg ), 3 );\n        S1 = SKP_SMLABB( S1, in16, B[ 2 ] );\n        tmp32    = SKP_RSHIFT_ROUND( out32, 13 ) + 1;\n        out[ k ] = (SKP_int16)SKP_SAT16( tmp32 );\n    }\n    S[ 0 ] = S0;\n    S[ 1 ] = S1;\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_biquad_alt.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_biquad_alt.c                                              *\n *                                                                      *\n * Second order ARMA filter                                             *\n * Can handle slowly varying filter coefficients                        *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n\n/* Second order ARMA filter, alternative implementation */\nvoid SKP_Silk_biquad_alt(\n    const SKP_int16      *in,            /* I:    Input signal                   */\n    const SKP_int32      *B_Q28,         /* I:    MA coefficients [3]            */\n    const SKP_int32      *A_Q28,         /* I:    AR coefficients [2]            */\n    SKP_int32            *S,             /* I/O: State vector [2]                */\n    SKP_int16            *out,           /* O:    Output signal                  */\n    const SKP_int32      len             /* I:    Signal length (must be even)   */\n)\n{\n    /* DIRECT FORM II TRANSPOSED (uses 2 element state vector) */\n    SKP_int   k;\n    SKP_int32 inval, A0_U_Q28, A0_L_Q28, A1_U_Q28, A1_L_Q28, out32_Q14;\n\n    /* Negate A_Q28 values and split in two parts */\n    A0_L_Q28 = ( -A_Q28[ 0 ] ) & 0x00003FFF;        /* lower part */\n    A0_U_Q28 = SKP_RSHIFT( -A_Q28[ 0 ], 14 );       /* upper part */\n    A1_L_Q28 = ( -A_Q28[ 1 ] ) & 0x00003FFF;        /* lower part */\n    A1_U_Q28 = SKP_RSHIFT( -A_Q28[ 1 ], 14 );       /* upper part */\n    \n    for( k = 0; k < len; k++ ) {\n        /* S[ 0 ], S[ 1 ]: Q12 */\n        inval = in[ k ];\n        out32_Q14 = SKP_LSHIFT( SKP_SMLAWB( S[ 0 ], B_Q28[ 0 ], inval ), 2 );\n\n        S[ 0 ] = S[1] + SKP_RSHIFT_ROUND( SKP_SMULWB( out32_Q14, A0_L_Q28 ), 14 );\n        S[ 0 ] = SKP_SMLAWB( S[ 0 ], out32_Q14, A0_U_Q28 );\n        S[ 0 ] = SKP_SMLAWB( S[ 0 ], B_Q28[ 1 ], inval);\n\n        S[ 1 ] = SKP_RSHIFT_ROUND( SKP_SMULWB( out32_Q14, A1_L_Q28 ), 14 );\n        S[ 1 ] = SKP_SMLAWB( S[ 1 ], out32_Q14, A1_U_Q28 );\n        S[ 1 ] = SKP_SMLAWB( S[ 1 ], B_Q28[ 2 ], inval );\n\n        /* Scale back to Q0 and saturate */\n        out[ k ] = (SKP_int16)SKP_SAT16( SKP_RSHIFT( out32_Q14 + (1<<14) - 1, 14 ) );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_burg_modified.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_burg_modified.c                                           *\n *                                                                      *\n * Calculates the reflection coefficients from the input vector         *\n * Input vector contains nb_subfr sub vectors of length L_sub + D       *\n *                                                                      *\n * Copyright 2009 (c), Skype Limited                                    *\n * Date: 100105                                                         *\n */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n#define MAX_FRAME_SIZE              544 // subfr_length * nb_subfr = ( 0.005 * 24000 + 16 ) * 4 = 544\n#define MAX_NB_SUBFR                4\n\n#define QA                          25\n#define N_BITS_HEAD_ROOM            2\n#define MIN_RSHIFTS                 -16\n#define MAX_RSHIFTS                 (32 - QA)\n\n/* Compute reflection coefficients from input signal */\nvoid SKP_Silk_burg_modified(\n    SKP_int32       *res_nrg,           /* O    residual energy                                                 */\n    SKP_int         *res_nrg_Q,         /* O    residual energy Q value                                         */\n    SKP_int32       A_Q16[],            /* O    prediction coefficients (length order)                          */\n    const SKP_int16 x[],                /* I    input signal, length: nb_subfr * ( D + subfr_length )           */\n    const SKP_int   subfr_length,       /* I    input signal subframe length (including D preceeding samples)   */\n    const SKP_int   nb_subfr,           /* I    number of subframes stacked in x                                */\n    const SKP_int32 WhiteNoiseFrac_Q32, /* I    fraction added to zero-lag autocorrelation                      */\n    const SKP_int   D                   /* I    order                                                           */\n)\n{\n    SKP_int         k, n, s, lz, rshifts, rshifts_extra;\n    SKP_int32       C0, num, nrg, rc_Q31, Atmp_QA, Atmp1, tmp1, tmp2, x1, x2;\n    const SKP_int16 *x_ptr;\n\n    SKP_int32       C_first_row[ SKP_Silk_MAX_ORDER_LPC ];\n    SKP_int32       C_last_row[  SKP_Silk_MAX_ORDER_LPC ];\n    SKP_int32       Af_QA[       SKP_Silk_MAX_ORDER_LPC ];\n\n    SKP_int32       CAf[ SKP_Silk_MAX_ORDER_LPC + 1 ];\n    SKP_int32       CAb[ SKP_Silk_MAX_ORDER_LPC + 1 ];\n\n    SKP_assert( subfr_length * nb_subfr <= MAX_FRAME_SIZE );\n    SKP_assert( nb_subfr <= MAX_NB_SUBFR );\n\n\n    /* Compute autocorrelations, added over subframes */\n    SKP_Silk_sum_sqr_shift( &C0, &rshifts, x, nb_subfr * subfr_length );\n    if( rshifts > MAX_RSHIFTS ) {\n        C0 = SKP_LSHIFT32( C0, rshifts - MAX_RSHIFTS );\n        SKP_assert( C0 > 0 );\n        rshifts = MAX_RSHIFTS;\n    } else {\n        lz = SKP_Silk_CLZ32( C0 ) - 1;\n        rshifts_extra = N_BITS_HEAD_ROOM - lz;\n        if( rshifts_extra > 0 ) {\n            rshifts_extra = SKP_min( rshifts_extra, MAX_RSHIFTS - rshifts );\n            C0 = SKP_RSHIFT32( C0, rshifts_extra );\n        } else {\n            rshifts_extra = SKP_max( rshifts_extra, MIN_RSHIFTS - rshifts );\n            C0 = SKP_LSHIFT32( C0, -rshifts_extra );\n        }\n        rshifts += rshifts_extra;\n    }\n    SKP_memset( C_first_row, 0, SKP_Silk_MAX_ORDER_LPC * sizeof( SKP_int32 ) );\n    if( rshifts > 0 ) {\n        for( s = 0; s < nb_subfr; s++ ) {\n            x_ptr = x + s * subfr_length;\n            for( n = 1; n < D + 1; n++ ) {\n                C_first_row[ n - 1 ] += (SKP_int32)SKP_RSHIFT64( \n                    SKP_Silk_inner_prod16_aligned_64( x_ptr, x_ptr + n, subfr_length - n ), rshifts );\n            }\n        }\n    } else {\n        for( s = 0; s < nb_subfr; s++ ) {\n            x_ptr = x + s * subfr_length;\n            for( n = 1; n < D + 1; n++ ) {\n                C_first_row[ n - 1 ] += SKP_LSHIFT32( \n                    SKP_Silk_inner_prod_aligned( x_ptr, x_ptr + n, subfr_length - n ), -rshifts );\n            }\n        }\n    }\n    SKP_memcpy( C_last_row, C_first_row, SKP_Silk_MAX_ORDER_LPC * sizeof( SKP_int32 ) );\n    \n    /* Initialize */\n    CAb[ 0 ] = CAf[ 0 ] = C0 + SKP_SMMUL( WhiteNoiseFrac_Q32, C0 ) + 1;         // Q(-rshifts)\n\n    for( n = 0; n < D; n++ ) {\n        /* Update first row of correlation matrix (without first element) */\n        /* Update last row of correlation matrix (without last element, stored in reversed order) */\n        /* Update C * Af */\n        /* Update C * flipud(Af) (stored in reversed order) */\n        if( rshifts > -2 ) {\n            for( s = 0; s < nb_subfr; s++ ) {\n                x_ptr = x + s * subfr_length;\n                x1  = -SKP_LSHIFT32( (SKP_int32)x_ptr[ n ],                    16 - rshifts );      // Q(16-rshifts)\n                x2  = -SKP_LSHIFT32( (SKP_int32)x_ptr[ subfr_length - n - 1 ], 16 - rshifts );      // Q(16-rshifts)\n                tmp1 = SKP_LSHIFT32( (SKP_int32)x_ptr[ n ],                    QA - 16 );           // Q(QA-16)\n                tmp2 = SKP_LSHIFT32( (SKP_int32)x_ptr[ subfr_length - n - 1 ], QA - 16 );           // Q(QA-16)\n                for( k = 0; k < n; k++ ) {\n                    C_first_row[ k ] = SKP_SMLAWB( C_first_row[ k ], x1, x_ptr[ n - k - 1 ]            ); // Q( -rshifts )\n                    C_last_row[ k ]  = SKP_SMLAWB( C_last_row[ k ],  x2, x_ptr[ subfr_length - n + k ] ); // Q( -rshifts )\n                    Atmp_QA = Af_QA[ k ];\n                    tmp1 = SKP_SMLAWB( tmp1, Atmp_QA, x_ptr[ n - k - 1 ]            );              // Q(QA-16)\n                    tmp2 = SKP_SMLAWB( tmp2, Atmp_QA, x_ptr[ subfr_length - n + k ] );              // Q(QA-16)\n                }\n                tmp1 = SKP_LSHIFT32( -tmp1, 32 - QA - rshifts );                                    // Q(16-rshifts)\n                tmp2 = SKP_LSHIFT32( -tmp2, 32 - QA - rshifts );                                    // Q(16-rshifts)\n                for( k = 0; k <= n; k++ ) {\n                    CAf[ k ] = SKP_SMLAWB( CAf[ k ], tmp1, x_ptr[ n - k ]                    );     // Q( -rshift )\n                    CAb[ k ] = SKP_SMLAWB( CAb[ k ], tmp2, x_ptr[ subfr_length - n + k - 1 ] );     // Q( -rshift )\n                }\n            }\n        } else {\n            for( s = 0; s < nb_subfr; s++ ) {\n                x_ptr = x + s * subfr_length;\n                x1  = -SKP_LSHIFT32( (SKP_int32)x_ptr[ n ],                    -rshifts );          // Q( -rshifts )\n                x2  = -SKP_LSHIFT32( (SKP_int32)x_ptr[ subfr_length - n - 1 ], -rshifts );          // Q( -rshifts )\n                tmp1 = SKP_LSHIFT32( (SKP_int32)x_ptr[ n ],                    17 );                // Q17\n                tmp2 = SKP_LSHIFT32( (SKP_int32)x_ptr[ subfr_length - n - 1 ], 17 );                // Q17\n                for( k = 0; k < n; k++ ) {\n                    C_first_row[ k ] = SKP_MLA( C_first_row[ k ], x1, x_ptr[ n - k - 1 ]            ); // Q( -rshifts )\n                    C_last_row[ k ]  = SKP_MLA( C_last_row[ k ],  x2, x_ptr[ subfr_length - n + k ] ); // Q( -rshifts )\n                    Atmp1 = SKP_RSHIFT_ROUND( Af_QA[ k ], QA - 17 );                                // Q17\n                    tmp1 = SKP_MLA( tmp1, x_ptr[ n - k - 1 ],            Atmp1 );                   // Q17\n                    tmp2 = SKP_MLA( tmp2, x_ptr[ subfr_length - n + k ], Atmp1 );                   // Q17\n                }\n                tmp1 = -tmp1;                                                                       // Q17\n                tmp2 = -tmp2;                                                                       // Q17\n                for( k = 0; k <= n; k++ ) {\n                    CAf[ k ] = SKP_SMLAWW( CAf[ k ], tmp1, \n                        SKP_LSHIFT32( (SKP_int32)x_ptr[ n - k ], -rshifts - 1 ) );                  // Q( -rshift )\n                    CAb[ k ] = SKP_SMLAWW( CAb[ k ], tmp2, \n                        SKP_LSHIFT32( (SKP_int32)x_ptr[ subfr_length - n + k - 1 ], -rshifts - 1 ) );// Q( -rshift )\n                }\n            }\n        }\n\n        /* Calculate nominator and denominator for the next order reflection (parcor) coefficient */\n        tmp1 = C_first_row[ n ];                                                            // Q( -rshifts )\n        tmp2 = C_last_row[ n ];                                                             // Q( -rshifts )\n        num  = 0;                                                                           // Q( -rshifts )\n        nrg  = SKP_ADD32( CAb[ 0 ], CAf[ 0 ] );                                             // Q( 1-rshifts )\n        for( k = 0; k < n; k++ ) {\n            Atmp_QA = Af_QA[ k ];\n            lz = SKP_Silk_CLZ32( SKP_abs( Atmp_QA ) ) - 1;\n            lz = SKP_min( 32 - QA, lz );\n            Atmp1 = SKP_LSHIFT32( Atmp_QA, lz );                                            // Q( QA + lz )\n\n            tmp1 = SKP_ADD_LSHIFT32( tmp1, SKP_SMMUL( C_last_row[  n - k - 1 ], Atmp1 ), 32 - QA - lz );    // Q( -rshifts )\n            tmp2 = SKP_ADD_LSHIFT32( tmp2, SKP_SMMUL( C_first_row[ n - k - 1 ], Atmp1 ), 32 - QA - lz );    // Q( -rshifts )\n            num  = SKP_ADD_LSHIFT32( num,  SKP_SMMUL( CAb[ n - k ],             Atmp1 ), 32 - QA - lz );    // Q( -rshifts )\n            nrg  = SKP_ADD_LSHIFT32( nrg,  SKP_SMMUL( SKP_ADD32( CAb[ k + 1 ], CAf[ k + 1 ] ), \n                                                                                Atmp1 ), 32 - QA - lz );    // Q( 1-rshifts )\n        }\n        CAf[ n + 1 ] = tmp1;                                                                // Q( -rshifts )\n        CAb[ n + 1 ] = tmp2;                                                                // Q( -rshifts )\n        num = SKP_ADD32( num, tmp2 );                                                       // Q( -rshifts )\n        num = SKP_LSHIFT32( -num, 1 );                                                      // Q( 1-rshifts )\n\n        /* Calculate the next order reflection (parcor) coefficient */\n        if( SKP_abs( num ) < nrg ) {\n            rc_Q31 = SKP_DIV32_varQ( num, nrg, 31 );\n        } else {\n            /* Negative energy or ratio too high; set remaining coefficients to zero and exit loop */\n            SKP_memset( &Af_QA[ n ], 0, ( D - n ) * sizeof( SKP_int32 ) );\n            SKP_assert( 0 );\n            break;\n        }\n\n        /* Update the AR coefficients */\n        for( k = 0; k < (n + 1) >> 1; k++ ) {\n            tmp1 = Af_QA[ k ];                                                              // QA\n            tmp2 = Af_QA[ n - k - 1 ];                                                      // QA\n            Af_QA[ k ]         = SKP_ADD_LSHIFT32( tmp1, SKP_SMMUL( tmp2, rc_Q31 ), 1 );    // QA\n            Af_QA[ n - k - 1 ] = SKP_ADD_LSHIFT32( tmp2, SKP_SMMUL( tmp1, rc_Q31 ), 1 );    // QA\n        }\n        Af_QA[ n ] = SKP_RSHIFT32( rc_Q31, 31 - QA );                                       // QA\n\n        /* Update C * Af and C * Ab */\n        for( k = 0; k <= n + 1; k++ ) {\n            tmp1 = CAf[ k ];                                                                // Q( -rshifts )\n            tmp2 = CAb[ n - k + 1 ];                                                        // Q( -rshifts )\n            CAf[ k ]         = SKP_ADD_LSHIFT32( tmp1, SKP_SMMUL( tmp2, rc_Q31 ), 1 );      // Q( -rshifts )\n            CAb[ n - k + 1 ] = SKP_ADD_LSHIFT32( tmp2, SKP_SMMUL( tmp1, rc_Q31 ), 1 );      // Q( -rshifts )\n        }\n    }\n\n    /* Return residual energy */\n    nrg  = CAf[ 0 ];                                                                        // Q( -rshifts )\n    tmp1 = 1 << 16;                                                                         // Q16\n    for( k = 0; k < D; k++ ) {\n        Atmp1 = SKP_RSHIFT_ROUND( Af_QA[ k ], QA - 16 );                                    // Q16\n        nrg  = SKP_SMLAWW( nrg, CAf[ k + 1 ], Atmp1 );                                      // Q( -rshifts )\n        tmp1 = SKP_SMLAWW( tmp1, Atmp1, Atmp1 );                                            // Q16\n        A_Q16[ k ] = -Atmp1;\n    }\n    *res_nrg = SKP_SMLAWW( nrg, SKP_SMMUL( WhiteNoiseFrac_Q32, C0 ), -tmp1 );               // Q( -rshifts )\n    *res_nrg_Q = -rshifts;\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_bwexpander.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Chirp (bandwidth expand) LP AR filter */\nvoid SKP_Silk_bwexpander( \n    SKP_int16            *ar,        /* I/O  AR filter to be expanded (without leading 1)    */\n    const SKP_int        d,          /* I    Length of ar                                    */\n    SKP_int32            chirp_Q16   /* I    Chirp factor (typically in the range 0 to 1)    */\n)\n{\n    SKP_int   i;\n    SKP_int32 chirp_minus_one_Q16;\n\n    chirp_minus_one_Q16 = chirp_Q16 - 65536;\n\n    /* NB: Dont use SKP_SMULWB, instead of SKP_RSHIFT_ROUND( SKP_MUL() , 16 ), below. */\n    /* Bias in SKP_SMULWB can lead to unstable filters                                */\n    for( i = 0; i < d - 1; i++ ) {\n        ar[ i ]    = (SKP_int16)SKP_RSHIFT_ROUND( SKP_MUL( chirp_Q16, ar[ i ]             ), 16 );\n        chirp_Q16 +=            SKP_RSHIFT_ROUND( SKP_MUL( chirp_Q16, chirp_minus_one_Q16 ), 16 );\n    }\n    ar[ d - 1 ] = (SKP_int16)SKP_RSHIFT_ROUND( SKP_MUL( chirp_Q16, ar[ d - 1 ] ), 16 );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_bwexpander_32.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Chirp (bandwidth expand) LP AR filter */\nvoid SKP_Silk_bwexpander_32( \n    SKP_int32        *ar,      /* I/O    AR filter to be expanded (without leading 1)    */\n    const SKP_int    d,        /* I    Length of ar                                      */\n    SKP_int32        chirp_Q16 /* I    Chirp factor in Q16                               */\n)\n{\n    SKP_int   i;\n    SKP_int32 tmp_chirp_Q16;\n\n    tmp_chirp_Q16 = chirp_Q16;\n    for( i = 0; i < d - 1; i++ ) {\n        ar[ i ]       = SKP_SMULWW( ar[ i ],   tmp_chirp_Q16 );\n        tmp_chirp_Q16 = SKP_SMULWW( chirp_Q16, tmp_chirp_Q16 );\n    }\n    ar[ d - 1 ] = SKP_SMULWW( ar[ d - 1 ], tmp_chirp_Q16 );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_code_signs.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n//#define SKP_enc_map(a)                ((a) > 0 ? 1 : 0)\n//#define SKP_dec_map(a)                ((a) > 0 ? 1 : -1)\n/* shifting avoids if-statement */\n#define SKP_enc_map(a)                  ( SKP_RSHIFT( (a), 15 ) + 1 )\n#define SKP_dec_map(a)                  ( SKP_LSHIFT( (a),  1 ) - 1 )\n\n/* Encodes signs of excitation */\nvoid SKP_Silk_encode_signs(\n    SKP_Silk_range_coder_state      *sRC,               /* I/O  Range coder state                       */\n    const SKP_int8                  q[],                /* I    Pulse signal                            */\n    const SKP_int                   length,             /* I    Length of input                         */\n    const SKP_int                   sigtype,            /* I    Signal type                             */\n    const SKP_int                   QuantOffsetType,    /* I    Quantization offset type                */\n    const SKP_int                   RateLevelIndex      /* I    Rate level index                        */\n)\n{\n    SKP_int i;\n    SKP_int inData;\n    SKP_uint16 cdf[ 3 ];\n\n    i = SKP_SMULBB( N_RATE_LEVELS - 1, SKP_LSHIFT( sigtype, 1 ) + QuantOffsetType ) + RateLevelIndex;\n    cdf[ 0 ] = 0;\n    cdf[ 1 ] = SKP_Silk_sign_CDF[ i ];\n    cdf[ 2 ] = 65535;\n    \n    for( i = 0; i < length; i++ ) {\n        if( q[ i ] != 0 ) {\n            inData = SKP_enc_map( q[ i ] ); /* - = 0, + = 1 */\n            SKP_Silk_range_encoder( sRC, inData, cdf );\n        }\n    }\n}\n\n/* Decodes signs of excitation */\nvoid SKP_Silk_decode_signs(\n    SKP_Silk_range_coder_state      *sRC,               /* I/O  Range coder state                           */\n    SKP_int                         q[],                /* I/O  pulse signal                                */\n    const SKP_int                   length,             /* I    length of output                            */\n    const SKP_int                   sigtype,            /* I    Signal type                                 */\n    const SKP_int                   QuantOffsetType,    /* I    Quantization offset type                    */\n    const SKP_int                   RateLevelIndex      /* I    Rate Level Index                            */\n)\n{\n    SKP_int i;\n    SKP_int data;\n    SKP_uint16 cdf[ 3 ];\n\n    i = SKP_SMULBB( N_RATE_LEVELS - 1, SKP_LSHIFT( sigtype, 1 ) + QuantOffsetType ) + RateLevelIndex;\n    cdf[ 0 ] = 0;\n    cdf[ 1 ] = SKP_Silk_sign_CDF[ i ];\n    cdf[ 2 ] = 65535;\n    \n    for( i = 0; i < length; i++ ) {\n        if( q[ i ] > 0 ) {\n            SKP_Silk_range_decoder( &data, sRC, cdf, 1 );\n            /* attach sign */\n            /* implementation with shift, subtraction, multiplication */\n            q[ i ] *= SKP_dec_map( data );\n        }\n    }\n}\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_control_audio_bandwidth.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n/* Control internal sampling rate */\nSKP_int SKP_Silk_control_audio_bandwidth(\n    SKP_Silk_encoder_state      *psEncC,            /* I/O  Pointer to Silk encoder state               */\n    const SKP_int32             TargetRate_bps      /* I    Target max bitrate (bps)                    */\n)\n{\n    SKP_int fs_kHz;\n\n    fs_kHz = psEncC->fs_kHz;\n    if( fs_kHz == 0 ) {\n        /* Encoder has just been initialized */\n        if( TargetRate_bps >= SWB2WB_BITRATE_BPS ) {\n            fs_kHz = 24;\n        } else if( TargetRate_bps >= WB2MB_BITRATE_BPS ) {\n            fs_kHz = 16;\n        } else if( TargetRate_bps >= MB2NB_BITRATE_BPS ) {\n            fs_kHz = 12;\n        } else {\n            fs_kHz = 8;\n        }\n        /* Make sure internal rate is not higher than external rate or maximum allowed, or lower than minimum allowed */\n        fs_kHz = SKP_min( fs_kHz, SKP_DIV32_16( psEncC->API_fs_Hz, 1000 ) );\n        fs_kHz = SKP_min( fs_kHz, psEncC->maxInternal_fs_kHz );\n    } else if( SKP_SMULBB( fs_kHz, 1000 ) > psEncC->API_fs_Hz || fs_kHz > psEncC->maxInternal_fs_kHz ) {\n        /* Make sure internal rate is not higher than external rate or maximum allowed */\n        fs_kHz = SKP_DIV32_16( psEncC->API_fs_Hz, 1000 );\n        fs_kHz = SKP_min( fs_kHz, psEncC->maxInternal_fs_kHz );\n    } else {\n        /* State machine for the internal sampling rate switching */\n        if( psEncC->API_fs_Hz > 8000 ) {\n            /* Accumulate the difference between the target rate and limit for switching down */\n            psEncC->bitrateDiff += SKP_MUL( psEncC->PacketSize_ms, TargetRate_bps - psEncC->bitrate_threshold_down );\n            psEncC->bitrateDiff  = SKP_min( psEncC->bitrateDiff, 0 );\n\n            if( psEncC->vadFlag == NO_VOICE_ACTIVITY ) { /* Low speech activity */\n                /* Check if we should switch down */\n#if SWITCH_TRANSITION_FILTERING \n                if( ( psEncC->sLP.transition_frame_no == 0 ) &&                         /* Transition phase not active */\n                    ( psEncC->bitrateDiff <= -ACCUM_BITS_DIFF_THRESHOLD ||              /* Bitrate threshold is met */\n                    ( psEncC->sSWBdetect.WB_detected * psEncC->fs_kHz == 24 ) ) ) {     /* Forced down-switching due to WB input */\n                        psEncC->sLP.transition_frame_no = 1;                            /* Begin transition phase */\n                        psEncC->sLP.mode                = 0;                            /* Switch down */\n                } else if( \n                    ( psEncC->sLP.transition_frame_no >= TRANSITION_FRAMES_DOWN ) &&    /* Transition phase complete */\n                    ( psEncC->sLP.mode == 0 ) ) {                                       /* Ready to switch down */\n                        psEncC->sLP.transition_frame_no = 0;                            /* Ready for new transition phase */\n#else\n                if( psEncC->bitrateDiff <= -ACCUM_BITS_DIFF_THRESHOLD ) {               /* Bitrate threshold is met */ \n#endif            \n                    psEncC->bitrateDiff = 0;\n\n                    /* Switch to a lower sample frequency */\n                    if( psEncC->fs_kHz == 24 ) {\n                        fs_kHz = 16;\n                    } else if( psEncC->fs_kHz == 16 ) {\n                        fs_kHz = 12;\n                    } else {\n                        SKP_assert( psEncC->fs_kHz == 12 );\n                        fs_kHz = 8;\n                    }\n                }\n\n                /* Check if we should switch up */\n                if( ( ( psEncC->fs_kHz * 1000 < psEncC->API_fs_Hz ) &&\n                    ( TargetRate_bps >= psEncC->bitrate_threshold_up ) && \n                    ( psEncC->sSWBdetect.WB_detected * psEncC->fs_kHz < 16 ) ) && \n                    ( ( ( psEncC->fs_kHz == 16 ) && ( psEncC->maxInternal_fs_kHz >= 24 ) ) || \n                    (   ( psEncC->fs_kHz == 12 ) && ( psEncC->maxInternal_fs_kHz >= 16 ) ) ||\n                    (   ( psEncC->fs_kHz ==  8 ) && ( psEncC->maxInternal_fs_kHz >= 12 ) ) ) \n#if SWITCH_TRANSITION_FILTERING\n                    && ( psEncC->sLP.transition_frame_no == 0 ) ) { /* No transition phase running, ready to switch */\n                        psEncC->sLP.mode = 1; /* Switch up */\n#else\n                    ) {\n#endif\n                    psEncC->bitrateDiff = 0;\n\n                    /* Switch to a higher sample frequency */\n                    if( psEncC->fs_kHz == 8 ) {\n                        fs_kHz = 12;\n                    } else if( psEncC->fs_kHz == 12 ) {\n                        fs_kHz = 16;\n                    } else {\n                        SKP_assert( psEncC->fs_kHz == 16 );\n                        fs_kHz = 24;\n                    }\n                }\n            }\n        }\n\n#if SWITCH_TRANSITION_FILTERING\n        /* After switching up, stop transition filter during speech inactivity */\n        if( ( psEncC->sLP.mode == 1 ) &&\n            ( psEncC->sLP.transition_frame_no >= TRANSITION_FRAMES_UP ) && \n            ( psEncC->vadFlag == NO_VOICE_ACTIVITY ) ) {\n\n                psEncC->sLP.transition_frame_no = 0;\n\n                /* Reset transition filter state */\n                SKP_memset( psEncC->sLP.In_LP_State, 0, 2 * sizeof( SKP_int32 ) );\n        }\n#endif\n    }\n\n\n\n    return fs_kHz;\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_control_codec_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n#include \"SKP_Silk_setup_complexity.h\"\n\nSKP_INLINE SKP_int SKP_Silk_setup_resamplers_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,             /* I/O  Pointer to Silk encoder state FIX       */\n    SKP_int                         fs_kHz              /* I    Internal sampling rate (kHz)            */\n);\n\nSKP_INLINE SKP_int SKP_Silk_setup_packetsize_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,             /* I/O  Pointer to Silk encoder state FIX       */\n    SKP_int                         PacketSize_ms       /* I    Packet length (ms)                      */\n);\n\nSKP_INLINE SKP_int SKP_Silk_setup_fs_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,             /* I/O  Pointer to Silk encoder state FIX       */\n    SKP_int                         fs_kHz              /* I    Internal sampling rate (kHz)            */\n);\n\nSKP_INLINE SKP_int SKP_Silk_setup_rate_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,             /* I/O  Pointer to Silk encoder state FIX       */\n    SKP_int32                       TargetRate_bps      /* I    Target max bitrate (if SNR_dB == 0)     */\n);\n\nSKP_INLINE SKP_int SKP_Silk_setup_LBRR_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc              /* I/O  Pointer to Silk encoder state FIX       */\n);\n\n/* Control encoder */\nSKP_int SKP_Silk_control_encoder_FIX( \n    SKP_Silk_encoder_state_FIX  *psEnc,                 /* I/O  Pointer to Silk encoder state           */\n    const SKP_int               PacketSize_ms,          /* I    Packet length (ms)                      */\n    const SKP_int32             TargetRate_bps,         /* I    Target max bitrate (bps)                */\n    const SKP_int               PacketLoss_perc,        /* I    Packet loss rate (in percent)           */\n    const SKP_int               DTX_enabled,            /* I    Enable / disable DTX                    */\n    const SKP_int               Complexity              /* I    Complexity (0->low; 1->medium; 2->high) */\n)\n{\n    SKP_int   fs_kHz, ret = 0;\n\n    if( psEnc->sCmn.controlled_since_last_payload != 0 ) {\n        if( psEnc->sCmn.API_fs_Hz != psEnc->sCmn.prev_API_fs_Hz && psEnc->sCmn.fs_kHz > 0 ) {\n            /* Change in API sampling rate in the middle of encoding a packet */\n            ret += SKP_Silk_setup_resamplers_FIX( psEnc, psEnc->sCmn.fs_kHz );\n        }\n        return ret;\n    }\n\n    /* Beyond this point we know that there are no previously coded frames in the payload buffer */\n\n    /********************************************/\n    /* Determine internal sampling rate         */\n    /********************************************/\n    fs_kHz = SKP_Silk_control_audio_bandwidth( &psEnc->sCmn, TargetRate_bps );\n\n    /********************************************/\n    /* Prepare resampler and buffered data      */\n    /********************************************/\n    ret += SKP_Silk_setup_resamplers_FIX( psEnc, fs_kHz );\n\n    /********************************************/\n    /* Set packet size                          */\n    /********************************************/\n    ret += SKP_Silk_setup_packetsize_FIX( psEnc, PacketSize_ms );\n\n    /********************************************/\n    /* Set internal sampling frequency          */\n    /********************************************/\n    ret += SKP_Silk_setup_fs_FIX( psEnc, fs_kHz );\n\n    /********************************************/\n    /* Set encoding complexity                  */\n    /********************************************/\n    ret += SKP_Silk_setup_complexity( &psEnc->sCmn, Complexity );\n\n    /********************************************/\n    /* Set bitrate/coding quality               */\n    /********************************************/\n    ret += SKP_Silk_setup_rate_FIX( psEnc, TargetRate_bps );\n\n    /********************************************/\n    /* Set packet loss rate measured by farend  */\n    /********************************************/\n    if( ( PacketLoss_perc < 0 ) || ( PacketLoss_perc > 100 ) ) {\n        ret = SKP_SILK_ENC_INVALID_LOSS_RATE;\n    }\n    psEnc->sCmn.PacketLoss_perc = PacketLoss_perc;\n\n    /********************************************/\n    /* Set LBRR usage                           */\n    /********************************************/\n    ret += SKP_Silk_setup_LBRR_FIX( psEnc );\n\n    /********************************************/\n    /* Set DTX mode                             */\n    /********************************************/\n    if( DTX_enabled < 0 || DTX_enabled > 1 ) {\n        ret = SKP_SILK_ENC_INVALID_DTX_SETTING;\n    }\n    psEnc->sCmn.useDTX = DTX_enabled;\n    psEnc->sCmn.controlled_since_last_payload = 1;\n\n    return ret;\n}\n\n/* Control low bitrate redundancy usage */\nvoid SKP_Silk_LBRR_ctrl_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,     /* I    Encoder state FIX                           */\n    SKP_Silk_encoder_control        *psEncCtrlC /* I/O  Encoder control                             */\n)\n{\n    SKP_int LBRR_usage;\n\n    if( psEnc->sCmn.LBRR_enabled ) {\n        /* Control LBRR */\n\n        /* Usage Control based on sensitivity and packet loss caracteristics */\n        /* For now only enable adding to next for active frames. Make more complex later */\n        LBRR_usage = SKP_SILK_NO_LBRR;\n        if( psEnc->speech_activity_Q8 > SKP_FIX_CONST( LBRR_SPEECH_ACTIVITY_THRES, 8 ) && psEnc->sCmn.PacketLoss_perc > LBRR_LOSS_THRES ) { // nb! maybe multiply loss prob and speech activity \n            LBRR_usage = SKP_SILK_ADD_LBRR_TO_PLUS1;\n        }\n        psEncCtrlC->LBRR_usage = LBRR_usage;\n    } else {\n        psEncCtrlC->LBRR_usage = SKP_SILK_NO_LBRR;\n    }\n}\n\nSKP_INLINE SKP_int SKP_Silk_setup_resamplers_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,             /* I/O  Pointer to Silk encoder state FIX       */\n    SKP_int                         fs_kHz              /* I    Internal sampling rate (kHz)            */\n)\n{\n    SKP_int ret = SKP_SILK_NO_ERROR;\n    \n    if( psEnc->sCmn.fs_kHz != fs_kHz || psEnc->sCmn.prev_API_fs_Hz != psEnc->sCmn.API_fs_Hz ) {\n\n        if( psEnc->sCmn.fs_kHz == 0 ) {\n            /* Initialize the resampler for enc_API.c preparing resampling from API_fs_Hz to fs_kHz */\n            ret += SKP_Silk_resampler_init( &psEnc->sCmn.resampler_state, psEnc->sCmn.API_fs_Hz, fs_kHz * 1000 );\n        } else {\n            /* Allocate space for worst case temporary upsampling, 8 to 48 kHz, so a factor 6 */\n            SKP_int16 x_buf_API_fs_Hz[ ( 2 * MAX_FRAME_LENGTH + LA_SHAPE_MAX ) * ( MAX_API_FS_KHZ / 8 ) ];\n\n            SKP_int32 nSamples_temp = SKP_LSHIFT( psEnc->sCmn.frame_length, 1 ) + LA_SHAPE_MS * psEnc->sCmn.fs_kHz;\n\n            if( SKP_SMULBB( fs_kHz, 1000 ) < psEnc->sCmn.API_fs_Hz && psEnc->sCmn.fs_kHz != 0 ) {\n                /* Resample buffered data in x_buf to API_fs_Hz */\n\n                SKP_Silk_resampler_state_struct  temp_resampler_state;\n\n                /* Initialize resampler for temporary resampling of x_buf data to API_fs_Hz */\n                ret += SKP_Silk_resampler_init( &temp_resampler_state, SKP_SMULBB( psEnc->sCmn.fs_kHz, 1000 ), psEnc->sCmn.API_fs_Hz );\n\n                /* Temporary resampling of x_buf data to API_fs_Hz */\n                ret += SKP_Silk_resampler( &temp_resampler_state, x_buf_API_fs_Hz, psEnc->x_buf, nSamples_temp );\n\n                /* Calculate number of samples that has been temporarily upsampled */\n                nSamples_temp = SKP_DIV32_16( nSamples_temp * psEnc->sCmn.API_fs_Hz, SKP_SMULBB( psEnc->sCmn.fs_kHz, 1000 ) );\n\n                /* Initialize the resampler for enc_API.c preparing resampling from API_fs_Hz to fs_kHz */\n                ret += SKP_Silk_resampler_init( &psEnc->sCmn.resampler_state, psEnc->sCmn.API_fs_Hz, SKP_SMULBB( fs_kHz, 1000 ) );\n\n            } else {\n                /* Copy data */\n                SKP_memcpy( x_buf_API_fs_Hz, psEnc->x_buf, nSamples_temp * sizeof( SKP_int16 ) );\n            }\n\n            if( 1000 * fs_kHz != psEnc->sCmn.API_fs_Hz ) {\n                /* Correct resampler state (unless resampling by a factor 1) by resampling buffered data from API_fs_Hz to fs_kHz */\n                ret += SKP_Silk_resampler( &psEnc->sCmn.resampler_state, psEnc->x_buf, x_buf_API_fs_Hz, nSamples_temp );\n            }\n        }\n    }\n\n    psEnc->sCmn.prev_API_fs_Hz = psEnc->sCmn.API_fs_Hz;\n\n    return(ret);\n}\n\nSKP_INLINE SKP_int SKP_Silk_setup_packetsize_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,             /* I/O  Pointer to Silk encoder state FIX       */\n    SKP_int                         PacketSize_ms       /* I    Packet length (ms)                      */\n)\n{\n    SKP_int ret = SKP_SILK_NO_ERROR;\n\n    /* Set packet size */\n    if( ( PacketSize_ms !=  20 ) && \n        ( PacketSize_ms !=  40 ) && \n        ( PacketSize_ms !=  60 ) && \n        ( PacketSize_ms !=  80 ) && \n        ( PacketSize_ms != 100 ) ) {\n        ret = SKP_SILK_ENC_PACKET_SIZE_NOT_SUPPORTED;\n    } else {\n        if( PacketSize_ms != psEnc->sCmn.PacketSize_ms ) {\n            psEnc->sCmn.PacketSize_ms = PacketSize_ms;\n\n            /* Packet length changes. Reset LBRR buffer */\n            SKP_Silk_LBRR_reset( &psEnc->sCmn );\n        }\n    }\n    return(ret);\n}\n\nSKP_INLINE SKP_int SKP_Silk_setup_fs_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,             /* I/O  Pointer to Silk encoder state FIX       */\n    SKP_int                         fs_kHz              /* I    Internal sampling rate (kHz)            */\n)\n{\n    SKP_int ret = SKP_SILK_NO_ERROR;\n\n    /* Set internal sampling frequency */\n    if( psEnc->sCmn.fs_kHz != fs_kHz ) {\n        /* reset part of the state */\n        SKP_memset( &psEnc->sShape,           0,                            sizeof( SKP_Silk_shape_state_FIX ) );\n        SKP_memset( &psEnc->sPrefilt,         0,                            sizeof( SKP_Silk_prefilter_state_FIX ) );\n        SKP_memset( &psEnc->sPred,            0,                            sizeof( SKP_Silk_predict_state_FIX ) );\n        SKP_memset( &psEnc->sCmn.sNSQ,        0,                            sizeof( SKP_Silk_nsq_state ) );\n        SKP_memset( psEnc->sCmn.sNSQ_LBRR.xq, 0, ( 2 * MAX_FRAME_LENGTH ) * sizeof( SKP_int16 ) );\n        SKP_memset( psEnc->sCmn.LBRR_buffer,  0,           MAX_LBRR_DELAY * sizeof( SKP_SILK_LBRR_struct ) );\n#if SWITCH_TRANSITION_FILTERING\n        SKP_memset( psEnc->sCmn.sLP.In_LP_State, 0, 2 * sizeof( SKP_int32 ) );\n        if( psEnc->sCmn.sLP.mode == 1 ) {\n            /* Begin transition phase */\n            psEnc->sCmn.sLP.transition_frame_no = 1;\n        } else {\n            /* End transition phase */\n            psEnc->sCmn.sLP.transition_frame_no = 0;\n        }\n#endif\n        psEnc->sCmn.inputBufIx          = 0;\n        psEnc->sCmn.nFramesInPayloadBuf = 0;\n        psEnc->sCmn.nBytesInPayloadBuf  = 0;\n        psEnc->sCmn.oldest_LBRR_idx     = 0;\n        psEnc->sCmn.TargetRate_bps      = 0; /* Ensures that psEnc->SNR_dB is recomputed */\n\n        SKP_memset( psEnc->sPred.prev_NLSFq_Q15, 0, MAX_LPC_ORDER * sizeof( SKP_int ) );\n\n        /* Initialize non-zero parameters */\n        psEnc->sCmn.prevLag                     = 100;\n        psEnc->sCmn.prev_sigtype                = SIG_TYPE_UNVOICED;\n        psEnc->sCmn.first_frame_after_reset     = 1;\n        psEnc->sPrefilt.lagPrev                 = 100;\n        psEnc->sShape.LastGainIndex             = 1;\n        psEnc->sCmn.sNSQ.lagPrev                = 100;\n        psEnc->sCmn.sNSQ.prev_inv_gain_Q16      = 65536;\n        psEnc->sCmn.sNSQ_LBRR.prev_inv_gain_Q16 = 65536;\n\n        psEnc->sCmn.fs_kHz = fs_kHz;\n        if( psEnc->sCmn.fs_kHz == 8 ) {\n            psEnc->sCmn.predictLPCOrder = MIN_LPC_ORDER;\n            psEnc->sCmn.psNLSF_CB[ 0 ]  = &SKP_Silk_NLSF_CB0_10;\n            psEnc->sCmn.psNLSF_CB[ 1 ]  = &SKP_Silk_NLSF_CB1_10;\n        } else {\n            psEnc->sCmn.predictLPCOrder = MAX_LPC_ORDER;\n            psEnc->sCmn.psNLSF_CB[ 0 ]  = &SKP_Silk_NLSF_CB0_16;\n            psEnc->sCmn.psNLSF_CB[ 1 ]  = &SKP_Silk_NLSF_CB1_16;\n        }\n        psEnc->sCmn.frame_length   = SKP_SMULBB( FRAME_LENGTH_MS, fs_kHz );\n        psEnc->sCmn.subfr_length   = SKP_DIV32_16( psEnc->sCmn.frame_length, NB_SUBFR );\n        psEnc->sCmn.la_pitch       = SKP_SMULBB( LA_PITCH_MS, fs_kHz );\n        psEnc->sPred.min_pitch_lag = SKP_SMULBB(  3, fs_kHz );\n        psEnc->sPred.max_pitch_lag = SKP_SMULBB( 18, fs_kHz );\n        psEnc->sPred.pitch_LPC_win_length = SKP_SMULBB( FIND_PITCH_LPC_WIN_MS, fs_kHz );\n        if( psEnc->sCmn.fs_kHz == 24 ) {\n            psEnc->mu_LTP_Q8 = SKP_FIX_CONST( MU_LTP_QUANT_SWB, 8 );\n            psEnc->sCmn.bitrate_threshold_up   = SKP_int32_MAX;\n            psEnc->sCmn.bitrate_threshold_down = SWB2WB_BITRATE_BPS; \n        } else if( psEnc->sCmn.fs_kHz == 16 ) {\n            psEnc->mu_LTP_Q8 = SKP_FIX_CONST( MU_LTP_QUANT_WB, 8 );\n            psEnc->sCmn.bitrate_threshold_up   = WB2SWB_BITRATE_BPS;\n            psEnc->sCmn.bitrate_threshold_down = WB2MB_BITRATE_BPS; \n        } else if( psEnc->sCmn.fs_kHz == 12 ) {\n            psEnc->mu_LTP_Q8 = SKP_FIX_CONST( MU_LTP_QUANT_MB, 8 );\n            psEnc->sCmn.bitrate_threshold_up   = MB2WB_BITRATE_BPS;\n            psEnc->sCmn.bitrate_threshold_down = MB2NB_BITRATE_BPS;\n        } else {\n            psEnc->mu_LTP_Q8 = SKP_FIX_CONST( MU_LTP_QUANT_NB, 8 );\n            psEnc->sCmn.bitrate_threshold_up   = NB2MB_BITRATE_BPS;\n            psEnc->sCmn.bitrate_threshold_down = 0;\n        }\n        psEnc->sCmn.fs_kHz_changed = 1;\n\n        /* Check that settings are valid */\n        SKP_assert( ( psEnc->sCmn.subfr_length * NB_SUBFR ) == psEnc->sCmn.frame_length );\n    }\n    return( ret );\n}\n\nSKP_INLINE SKP_int SKP_Silk_setup_rate_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,             /* I/O  Pointer to Silk encoder state FIX       */\n    SKP_int32                       TargetRate_bps      /* I    Target max bitrate (if SNR_dB == 0)     */\n)\n{\n    SKP_int k, ret = SKP_SILK_NO_ERROR;\n    SKP_int32 frac_Q6;\n    const SKP_int32 *rateTable;\n\n    /* Set bitrate/coding quality */\n    if( TargetRate_bps != psEnc->sCmn.TargetRate_bps ) {\n        psEnc->sCmn.TargetRate_bps = TargetRate_bps;\n\n        /* If new TargetRate_bps, translate to SNR_dB value */\n        if( psEnc->sCmn.fs_kHz == 8 ) {\n            rateTable = TargetRate_table_NB;\n        } else if( psEnc->sCmn.fs_kHz == 12 ) {\n            rateTable = TargetRate_table_MB;\n        } else if( psEnc->sCmn.fs_kHz == 16 ) {\n            rateTable = TargetRate_table_WB;\n        } else {\n            rateTable = TargetRate_table_SWB;\n        }\n        for( k = 1; k < TARGET_RATE_TAB_SZ; k++ ) {\n            /* Find bitrate interval in table and interpolate */\n            if( TargetRate_bps <= rateTable[ k ] ) {\n                frac_Q6 = SKP_DIV32( SKP_LSHIFT( TargetRate_bps - rateTable[ k - 1 ], 6 ), \n                                                 rateTable[ k ] - rateTable[ k - 1 ] );\n                psEnc->SNR_dB_Q7 = SKP_LSHIFT( SNR_table_Q1[ k - 1 ], 6 ) + SKP_MUL( frac_Q6, SNR_table_Q1[ k ] - SNR_table_Q1[ k - 1 ] );\n                break;\n            }\n        }\n    }\n    return( ret );\n}\n\nSKP_INLINE SKP_int SKP_Silk_setup_LBRR_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc              /* I/O  Pointer to Silk encoder state FIX       */\n)\n{\n    SKP_int   ret = SKP_SILK_NO_ERROR;\n#if USE_LBRR\n    SKP_int32 LBRRRate_thres_bps;\n\n    if( psEnc->sCmn.useInBandFEC < 0 || psEnc->sCmn.useInBandFEC > 1 ) {\n        ret = SKP_SILK_ENC_INVALID_INBAND_FEC_SETTING;\n    }\n    \n    psEnc->sCmn.LBRR_enabled = psEnc->sCmn.useInBandFEC;\n    if( psEnc->sCmn.fs_kHz == 8 ) {\n        LBRRRate_thres_bps = INBAND_FEC_MIN_RATE_BPS - 9000;\n    } else if( psEnc->sCmn.fs_kHz == 12 ) {\n        LBRRRate_thres_bps = INBAND_FEC_MIN_RATE_BPS - 6000;;\n    } else if( psEnc->sCmn.fs_kHz == 16 ) {\n        LBRRRate_thres_bps = INBAND_FEC_MIN_RATE_BPS - 3000;\n    } else {\n        LBRRRate_thres_bps = INBAND_FEC_MIN_RATE_BPS;\n    }\n\n    if( psEnc->sCmn.TargetRate_bps >= LBRRRate_thres_bps ) {\n        /* Set gain increase / rate reduction for LBRR usage */\n        /* Coarsely tuned with PESQ for now. */\n        /* Linear regression coefs G = 8 - 0.5 * loss */\n        /* Meaning that at 16% loss main rate and redundant rate is the same, -> G = 0 */\n        psEnc->sCmn.LBRR_GainIncreases = SKP_max_int( 8 - SKP_RSHIFT( psEnc->sCmn.PacketLoss_perc, 1 ), 0 );\n\n        /* Set main stream rate compensation */\n        if( psEnc->sCmn.LBRR_enabled && psEnc->sCmn.PacketLoss_perc > LBRR_LOSS_THRES ) {\n            /* Tuned to give approx same mean / weighted bitrate as no inband FEC */\n            psEnc->inBandFEC_SNR_comp_Q8 = SKP_FIX_CONST( 6.0f, 8 ) - SKP_LSHIFT( psEnc->sCmn.LBRR_GainIncreases, 7 );\n        } else {\n            psEnc->inBandFEC_SNR_comp_Q8 = 0;\n            psEnc->sCmn.LBRR_enabled     = 0;\n        }\n    } else {\n        psEnc->inBandFEC_SNR_comp_Q8     = 0;\n        psEnc->sCmn.LBRR_enabled         = 0;\n    }\n#else\n    if( INBandFEC_enabled != 0 ) {\n        ret = SKP_SILK_ENC_INVALID_INBAND_FEC_SETTING;\n    }\n    psEnc->sCmn.LBRR_enabled = 0;\n#endif\n    return ret;\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_corrMatrix_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/**********************************************************************\n * Correlation Matrix Computations for LS estimate. \n **********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\n/* Calculates correlation vector X'*t */\nvoid SKP_Silk_corrVector_FIX(\n    const SKP_int16                 *x,         /* I    x vector [L + order - 1] used to form data matrix X */\n    const SKP_int16                 *t,         /* I    target vector [L]                                   */\n    const SKP_int                   L,          /* I    Length of vectors                                   */\n    const SKP_int                   order,      /* I    Max lag for correlation                             */\n    SKP_int32                       *Xt,        /* O    Pointer to X'*t correlation vector [order]          */\n    const SKP_int                   rshifts     /* I    Right shifts of correlations                        */\n)\n{\n    SKP_int         lag, i;\n    const SKP_int16 *ptr1, *ptr2;\n    SKP_int32       inner_prod;\n\n    ptr1 = &x[ order - 1 ]; /* Points to first sample of column 0 of X: X[:,0] */\n    ptr2 = t;\n    /* Calculate X'*t */\n    if( rshifts > 0 ) {\n        /* Right shifting used */\n        for( lag = 0; lag < order; lag++ ) {\n            inner_prod = 0;\n            for( i = 0; i < L; i++ ) {\n                inner_prod += SKP_RSHIFT32( SKP_SMULBB( ptr1[ i ], ptr2[i] ), rshifts );\n            }\n            Xt[ lag ] = inner_prod; /* X[:,lag]'*t */\n            ptr1--; /* Go to next column of X */\n        }\n    } else {\n        SKP_assert( rshifts == 0 );\n        for( lag = 0; lag < order; lag++ ) {\n            Xt[ lag ] = SKP_Silk_inner_prod_aligned( ptr1, ptr2, L ); /* X[:,lag]'*t */\n            ptr1--; /* Go to next column of X */\n        }\n    }\n}\n\n/* Calculates correlation matrix X'*X */\nvoid SKP_Silk_corrMatrix_FIX(\n    const SKP_int16                 *x,         /* I    x vector [L + order - 1] used to form data matrix X */\n    const SKP_int                   L,          /* I    Length of vectors                                   */\n    const SKP_int                   order,      /* I    Max lag for correlation                             */\n    const SKP_int                   head_room,  /* I    Desired headroom                                    */\n    SKP_int32                       *XX,        /* O    Pointer to X'*X correlation matrix [ order x order ]*/\n    SKP_int                         *rshifts    /* I/O  Right shifts of correlations                        */\n)\n{\n    SKP_int         i, j, lag, rshifts_local, head_room_rshifts;\n    SKP_int32       energy;\n    const SKP_int16 *ptr1, *ptr2;\n\n    /* Calculate energy to find shift used to fit in 32 bits */\n    SKP_Silk_sum_sqr_shift( &energy, &rshifts_local, x, L + order - 1 );\n\n    /* Add shifts to get the desired head room */\n    head_room_rshifts = SKP_max( head_room - SKP_Silk_CLZ32( energy ), 0 );\n    \n    energy = SKP_RSHIFT32( energy, head_room_rshifts );\n    rshifts_local += head_room_rshifts;\n\n    /* Calculate energy of first column (0) of X: X[:,0]'*X[:,0] */\n    /* Remove contribution of first order - 1 samples */\n    for( i = 0; i < order - 1; i++ ) {\n        energy -= SKP_RSHIFT32( SKP_SMULBB( x[ i ], x[ i ] ), rshifts_local );\n    }\n    if( rshifts_local < *rshifts ) {\n        /* Adjust energy */\n        energy = SKP_RSHIFT32( energy, *rshifts - rshifts_local );\n        rshifts_local = *rshifts;\n    }\n\n    /* Calculate energy of remaining columns of X: X[:,j]'*X[:,j] */\n    /* Fill out the diagonal of the correlation matrix */\n    matrix_ptr( XX, 0, 0, order ) = energy;\n    ptr1 = &x[ order - 1 ]; /* First sample of column 0 of X */\n    for( j = 1; j < order; j++ ) {\n        energy = SKP_SUB32( energy, SKP_RSHIFT32( SKP_SMULBB( ptr1[ L - j ], ptr1[ L - j ] ), rshifts_local ) );\n        energy = SKP_ADD32( energy, SKP_RSHIFT32( SKP_SMULBB( ptr1[ -j ], ptr1[ -j ] ), rshifts_local ) );\n        matrix_ptr( XX, j, j, order ) = energy;\n    }\n\n    ptr2 = &x[ order - 2 ]; /* First sample of column 1 of X */\n    /* Calculate the remaining elements of the correlation matrix */\n    if( rshifts_local > 0 ) {\n        /* Right shifting used */\n        for( lag = 1; lag < order; lag++ ) {\n            /* Inner product of column 0 and column lag: X[:,0]'*X[:,lag] */\n            energy = 0;\n            for( i = 0; i < L; i++ ) {\n                energy += SKP_RSHIFT32( SKP_SMULBB( ptr1[ i ], ptr2[i] ), rshifts_local );\n            }\n            /* Calculate remaining off diagonal: X[:,j]'*X[:,j + lag] */\n            matrix_ptr( XX, lag, 0, order ) = energy;\n            matrix_ptr( XX, 0, lag, order ) = energy;\n            for( j = 1; j < ( order - lag ); j++ ) {\n                energy = SKP_SUB32( energy, SKP_RSHIFT32( SKP_SMULBB( ptr1[ L - j ], ptr2[ L - j ] ), rshifts_local ) );\n                energy = SKP_ADD32( energy, SKP_RSHIFT32( SKP_SMULBB( ptr1[ -j ], ptr2[ -j ] ), rshifts_local ) );\n                matrix_ptr( XX, lag + j, j, order ) = energy;\n                matrix_ptr( XX, j, lag + j, order ) = energy;\n            }\n            ptr2--; /* Update pointer to first sample of next column (lag) in X */\n        }\n    } else {\n        for( lag = 1; lag < order; lag++ ) {\n            /* Inner product of column 0 and column lag: X[:,0]'*X[:,lag] */\n            energy = SKP_Silk_inner_prod_aligned( ptr1, ptr2, L );\n            matrix_ptr( XX, lag, 0, order ) = energy;\n            matrix_ptr( XX, 0, lag, order ) = energy;\n            /* Calculate remaining off diagonal: X[:,j]'*X[:,j + lag] */\n            for( j = 1; j < ( order - lag ); j++ ) {\n                energy = SKP_SUB32( energy, SKP_SMULBB( ptr1[ L - j ], ptr2[ L - j ] ) );\n                energy = SKP_SMLABB( energy, ptr1[ -j ], ptr2[ -j ] );\n                matrix_ptr( XX, lag + j, j, order ) = energy;\n                matrix_ptr( XX, j, lag + j, order ) = energy;\n            }\n            ptr2--;/* Update pointer to first sample of next column (lag) in X */\n        }\n    }\n    *rshifts = rshifts_local;\n}\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_create_init_destroy.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n\n/************************/\n/* Init Decoder State   */\n/************************/\nSKP_int SKP_Silk_init_decoder(\n    SKP_Silk_decoder_state      *psDec              /* I/O  Decoder state pointer                       */\n)\n{\n    SKP_memset( psDec, 0, sizeof( SKP_Silk_decoder_state ) );\n    /* Set sampling rate to 24 kHz, and init non-zero values */\n    SKP_Silk_decoder_set_fs( psDec, 24 );\n\n    /* Used to deactivate e.g. LSF interpolation and fluctuation reduction */\n    psDec->first_frame_after_reset = 1;\n    psDec->prev_inv_gain_Q16 = 65536;\n\n    /* Reset CNG state */\n    SKP_Silk_CNG_Reset( psDec );\n\n    SKP_Silk_PLC_Reset( psDec );\n    \n    return(0);\n}\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_dec_API.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_SDK_API.h\"\n#include \"SKP_Silk_main.h\"\n\n/*********************/\n/* Decoder functions */\n/*********************/\n\nSKP_int SKP_Silk_SDK_Get_Decoder_Size( SKP_int32 *decSizeBytes ) \n{\n    SKP_int ret = 0;\n\n    *decSizeBytes = sizeof( SKP_Silk_decoder_state );\n\n    return ret;\n}\n\n/* Reset decoder state */\nSKP_int SKP_Silk_SDK_InitDecoder(\n    void* decState                                      /* I/O: State                                          */\n)\n{\n    SKP_int ret = 0;\n    SKP_Silk_decoder_state *struc;\n\n    struc = (SKP_Silk_decoder_state *)decState;\n\n    ret  = SKP_Silk_init_decoder( struc );\n\n    return ret;\n}\n\n/* Decode a frame */\nSKP_int SKP_Silk_SDK_Decode(\n    void*                               decState,       /* I/O: State                                           */\n    SKP_SILK_SDK_DecControlStruct*      decControl,     /* I/O: Control structure                               */\n    SKP_int                             lostFlag,       /* I:   0: no loss, 1 loss                              */\n    const SKP_uint8                     *inData,        /* I:   Encoded input vector                            */\n    const SKP_int                       nBytesIn,       /* I:   Number of input Bytes                           */\n    SKP_int16                           *samplesOut,    /* O:   Decoded output speech vector                    */\n    SKP_int16                           *nSamplesOut    /* I/O: Number of samples (vector/decoded)              */\n)\n{\n    SKP_int ret = 0, used_bytes, prev_fs_kHz;\n    SKP_Silk_decoder_state *psDec;\n    SKP_int16 samplesOutInternal[ MAX_API_FS_KHZ * FRAME_LENGTH_MS ];\n    SKP_int16 *pSamplesOutInternal;\n\n    psDec = (SKP_Silk_decoder_state *)decState;\n\n    /* We need this buffer to have room for an internal frame */\n    pSamplesOutInternal = samplesOut;\n    if( psDec->fs_kHz * 1000 > decControl->API_sampleRate ) {\n        pSamplesOutInternal = samplesOutInternal;\n    }\n\n    /**********************************/\n    /* Test if first frame in payload */\n    /**********************************/\n    if( psDec->moreInternalDecoderFrames == 0 ) {\n        /* First Frame in Payload */\n        psDec->nFramesDecoded = 0;  /* Used to count frames in packet */\n    }\n\n    if( psDec->moreInternalDecoderFrames == 0 &&    /* First frame in packet    */\n        lostFlag == 0 &&                            /* Not packet loss          */\n        nBytesIn > MAX_ARITHM_BYTES ) {             /* Too long payload         */\n            /* Avoid trying to decode a too large packet */\n            lostFlag = 1;\n            ret = SKP_SILK_DEC_PAYLOAD_TOO_LARGE;\n    }\n            \n    /* Save previous sample frequency */\n    prev_fs_kHz = psDec->fs_kHz;\n    \n    /* Call decoder for one frame */\n    ret += SKP_Silk_decode_frame( psDec, pSamplesOutInternal, nSamplesOut, inData, nBytesIn, \n            lostFlag, &used_bytes );\n    \n    if( used_bytes ) { /* Only Call if not a packet loss */\n        if( psDec->nBytesLeft > 0 && psDec->FrameTermination == SKP_SILK_MORE_FRAMES && psDec->nFramesDecoded < 5 ) {\n            /* We have more frames in the Payload */\n            psDec->moreInternalDecoderFrames = 1;\n        } else {\n            /* Last frame in Payload */\n            psDec->moreInternalDecoderFrames = 0;\n            psDec->nFramesInPacket = psDec->nFramesDecoded;\n        \n            /* Track inband FEC usage */\n            if( psDec->vadFlag == VOICE_ACTIVITY ) {\n                if( psDec->FrameTermination == SKP_SILK_LAST_FRAME ) {\n                    psDec->no_FEC_counter++;\n                    if( psDec->no_FEC_counter > NO_LBRR_THRES ) {\n                        psDec->inband_FEC_offset = 0;\n                    }\n                } else if( psDec->FrameTermination == SKP_SILK_LBRR_VER1 ) {\n                    psDec->inband_FEC_offset = 1; /* FEC info with 1 packet delay */\n                    psDec->no_FEC_counter    = 0;\n                } else if( psDec->FrameTermination == SKP_SILK_LBRR_VER2 ) {\n                    psDec->inband_FEC_offset = 2; /* FEC info with 2 packets delay */\n                    psDec->no_FEC_counter    = 0;\n                }\n            }\n        }\n    }\n\n    if( MAX_API_FS_KHZ * 1000 < decControl->API_sampleRate ||\n        8000       > decControl->API_sampleRate ) {\n        ret = SKP_SILK_DEC_INVALID_SAMPLING_FREQUENCY;\n        return( ret );\n    }\n\n    /* Resample if needed */\n    if( psDec->fs_kHz * 1000 != decControl->API_sampleRate ) { \n        SKP_int16 samplesOut_tmp[ MAX_API_FS_KHZ * FRAME_LENGTH_MS ];\n        SKP_assert( psDec->fs_kHz <= MAX_API_FS_KHZ );\n\n        /* Copy to a tmp buffer as the resampling writes to samplesOut */\n        SKP_memcpy( samplesOut_tmp, pSamplesOutInternal, *nSamplesOut * sizeof( SKP_int16 ) );\n\n        /* (Re-)initialize resampler state when switching internal sampling frequency */\n        if( prev_fs_kHz != psDec->fs_kHz || psDec->prev_API_sampleRate != decControl->API_sampleRate ) {\n            ret = SKP_Silk_resampler_init( &psDec->resampler_state, SKP_SMULBB( psDec->fs_kHz, 1000 ), decControl->API_sampleRate );\n        }\n\n        /* Resample the output to API_sampleRate */\n        ret += SKP_Silk_resampler( &psDec->resampler_state, samplesOut, samplesOut_tmp, *nSamplesOut );\n\n        /* Update the number of output samples */\n        *nSamplesOut = SKP_DIV32( ( SKP_int32 )*nSamplesOut * decControl->API_sampleRate, psDec->fs_kHz * 1000 );\n    } else if( prev_fs_kHz * 1000 > decControl->API_sampleRate ) { \n        SKP_memcpy( samplesOut, pSamplesOutInternal, *nSamplesOut * sizeof( SKP_int16 ) );\n    }\n\n    psDec->prev_API_sampleRate = decControl->API_sampleRate;\n\n    /* Copy all parameters that are needed out of internal structure to the control stucture */\n    decControl->frameSize                 = (SKP_uint16)( decControl->API_sampleRate / 50 ) ;\n    decControl->framesPerPacket           = ( SKP_int )psDec->nFramesInPacket;\n    decControl->inBandFECOffset           = ( SKP_int )psDec->inband_FEC_offset;\n    decControl->moreInternalDecoderFrames = ( SKP_int )psDec->moreInternalDecoderFrames;\n\n    return ret;\n}\n\n/* Function to find LBRR information in a packet */\nvoid SKP_Silk_SDK_search_for_LBRR(\n    const SKP_uint8                     *inData,        /* I:   Encoded input vector                            */\n    const SKP_int                       nBytesIn,       /* I:   Number of input Bytes                           */\n    SKP_int                             lost_offset,    /* I:   Offset from lost packet                         */\n    SKP_uint8                           *LBRRData,      /* O:   LBRR payload                                    */\n    SKP_int16                           *nLBRRBytes     /* O:   Number of LBRR Bytes                            */\n)\n{\n    SKP_Silk_decoder_state   sDec; // Local decoder state to avoid interfering with running decoder */\n    SKP_Silk_decoder_control sDecCtrl;\n    SKP_int TempQ[ MAX_FRAME_LENGTH ];\n\n    if( lost_offset < 1 || lost_offset > MAX_LBRR_DELAY ) {\n        /* No useful FEC in this packet */\n        *nLBRRBytes = 0;\n        return;\n    }\n\n    sDec.nFramesDecoded = 0;\n    sDec.fs_kHz         = 0; /* Force update parameters LPC_order etc */\n\tsDec.lossCnt        = 0; /* Avoid running bw expansion of the LPC parameters when searching for LBRR data */\n    SKP_memset( sDec.prevNLSF_Q15, 0, MAX_LPC_ORDER * sizeof( SKP_int ) );\n    SKP_Silk_range_dec_init( &sDec.sRC, inData, ( SKP_int32 )nBytesIn );\n    \n    while(1) {\n        SKP_Silk_decode_parameters( &sDec, &sDecCtrl, TempQ, 0 );\n    \n        if( sDec.sRC.error ) {\n            /* Corrupt stream */\n            *nLBRRBytes = 0;\n            return;\n        };\n        if( ( sDec.FrameTermination - 1 ) & lost_offset && sDec.FrameTermination > 0 && sDec.nBytesLeft >= 0 ) {\n            /* The wanted FEC is present in the packet */\n            *nLBRRBytes = sDec.nBytesLeft;\n            SKP_memcpy( LBRRData, &inData[ nBytesIn - sDec.nBytesLeft ], sDec.nBytesLeft * sizeof( SKP_uint8 ) );\n            break;\n        }\n        if( sDec.nBytesLeft > 0 && sDec.FrameTermination == SKP_SILK_MORE_FRAMES ) {\n            sDec.nFramesDecoded++;\n        } else {\n            LBRRData = NULL;\n            *nLBRRBytes = 0;\n            break;\n        }\n    }\n}\n\n/* Getting type of content for a packet */\nvoid SKP_Silk_SDK_get_TOC(\n    const SKP_uint8                     *inData,        /* I:   Encoded input vector                            */\n    const SKP_int                       nBytesIn,       /* I:   Number of input bytes                           */\n    SKP_Silk_TOC_struct                 *Silk_TOC       /* O:   Type of content                                 */\n)\n{\n    SKP_Silk_decoder_state      sDec; // Local Decoder state to avoid interfering with running decoder */\n    SKP_Silk_decoder_control    sDecCtrl;\n    SKP_int TempQ[ MAX_FRAME_LENGTH ];\n\n    sDec.nFramesDecoded = 0;\n    sDec.fs_kHz         = 0; /* Force update parameters LPC_order etc */\n    SKP_Silk_range_dec_init( &sDec.sRC, inData, ( SKP_int32 )nBytesIn );\n\n    Silk_TOC->corrupt = 0;\n    while( 1 ) {\n        SKP_Silk_decode_parameters( &sDec, &sDecCtrl, TempQ, 0 );\n        \n        Silk_TOC->vadFlags[     sDec.nFramesDecoded ] = sDec.vadFlag;\n        Silk_TOC->sigtypeFlags[ sDec.nFramesDecoded ] = sDecCtrl.sigtype;\n    \n        if( sDec.sRC.error ) {\n            /* Corrupt stream */\n            Silk_TOC->corrupt = 1;\n            break;\n        };\n    \n        if( sDec.nBytesLeft > 0 && sDec.FrameTermination == SKP_SILK_MORE_FRAMES ) {\n            sDec.nFramesDecoded++;\n        } else {\n            break;\n        }\n    }\n    if( Silk_TOC->corrupt || sDec.FrameTermination == SKP_SILK_MORE_FRAMES || \n        sDec.nFramesInPacket > SILK_MAX_FRAMES_PER_PACKET ) {\n        /* Corrupt packet */\n        SKP_memset( Silk_TOC, 0, sizeof( SKP_Silk_TOC_struct ) );\n        Silk_TOC->corrupt = 1;\n    } else {\n        Silk_TOC->framesInPacket = sDec.nFramesDecoded + 1;\n        Silk_TOC->fs_kHz         = sDec.fs_kHz;\n        if( sDec.FrameTermination == SKP_SILK_LAST_FRAME ) {\n            Silk_TOC->inbandLBRR = sDec.FrameTermination;\n        } else {\n            Silk_TOC->inbandLBRR = sDec.FrameTermination - 1;\n        }\n    }\n}\n\n/**************************/\n/* Get the version number */\n/**************************/\n/* Return a pointer to string specifying the version */ \nconst char *SKP_Silk_SDK_get_version()\n{\n    static const char version[] = \"1.0.9\";\n    return version;\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_decode_core.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n\nvoid SKP_Silk_decode_short_term_prediction(\nSKP_int32\t*vec_Q10,\nSKP_int32\t*pres_Q10,\nSKP_int32\t*sLPC_Q14,\nSKP_int16\t*A_Q12_tmp, \nSKP_int\t\tLPC_order,\nSKP_int\t\tsubfr_length\n);\n\n\n/**********************************************************/\n/* Core decoder. Performs inverse NSQ operation LTP + LPC */\n/**********************************************************/\nvoid SKP_Silk_decode_core(\n    SKP_Silk_decoder_state      *psDec,                             /* I/O  Decoder state               */\n    SKP_Silk_decoder_control    *psDecCtrl,                         /* I    Decoder control             */\n    SKP_int16                   xq[],                               /* O    Decoded speech              */\n    const SKP_int               q[ MAX_FRAME_LENGTH ]               /* I    Pulse signal                */\n)\n{\n    SKP_int   i, k, lag = 0, start_idx, sLTP_buf_idx, NLSF_interpolation_flag, sigtype;\n    SKP_int16 *A_Q12, *B_Q14, *pxq, A_Q12_tmp[ MAX_LPC_ORDER ];\n    SKP_int16 sLTP[ MAX_FRAME_LENGTH ];\n    SKP_int32 LTP_pred_Q14, Gain_Q16, inv_gain_Q16, inv_gain_Q32, gain_adj_Q16, rand_seed, offset_Q10, dither;\n    SKP_int32 *pred_lag_ptr, *pexc_Q10, *pres_Q10;\n    SKP_int32 vec_Q10[ MAX_FRAME_LENGTH / NB_SUBFR ];\n    SKP_int32 FiltState[ MAX_LPC_ORDER ];\n\n    SKP_assert( psDec->prev_inv_gain_Q16 != 0 );\n    \n    offset_Q10 = SKP_Silk_Quantization_Offsets_Q10[ psDecCtrl->sigtype ][ psDecCtrl->QuantOffsetType ];\n\n    if( psDecCtrl->NLSFInterpCoef_Q2 < ( 1 << 2 ) ) {\n        NLSF_interpolation_flag = 1;\n    } else {\n        NLSF_interpolation_flag = 0;\n    }\n\n\n    /* Decode excitation */\n    rand_seed = psDecCtrl->Seed;\n    for( i = 0; i < psDec->frame_length; i++ ) {\n        rand_seed = SKP_RAND( rand_seed );\n        /* dither = rand_seed < 0 ? 0xFFFFFFFF : 0; */\n        dither = SKP_RSHIFT( rand_seed, 31 );\n\n        psDec->exc_Q10[ i ] = SKP_LSHIFT( ( SKP_int32 )q[ i ], 10 ) + offset_Q10;\n        psDec->exc_Q10[ i ] = ( psDec->exc_Q10[ i ] ^ dither ) - dither;\n\n        rand_seed += q[ i ];\n    }\n\n\n    pexc_Q10 = psDec->exc_Q10;\n    pres_Q10 = psDec->res_Q10;\n    pxq      = &psDec->outBuf[ psDec->frame_length ];\n    sLTP_buf_idx = psDec->frame_length;\n    /* Loop over subframes */\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        A_Q12 = psDecCtrl->PredCoef_Q12[ k >> 1 ];\n\n        /* Preload LPC coeficients to array on stack. Gives small performance gain */        \n        SKP_memcpy( A_Q12_tmp, A_Q12, psDec->LPC_order * sizeof( SKP_int16 ) ); \n        B_Q14         = &psDecCtrl->LTPCoef_Q14[ k * LTP_ORDER ];\n        Gain_Q16      = psDecCtrl->Gains_Q16[ k ];\n        sigtype       = psDecCtrl->sigtype;\n\n        inv_gain_Q16 = SKP_INVERSE32_varQ( SKP_max( Gain_Q16, 1 ), 32 );\n        inv_gain_Q16 = SKP_min( inv_gain_Q16, SKP_int16_MAX );\n\n        /* Calculate Gain adjustment factor */\n        gain_adj_Q16 = ( SKP_int32 )1 << 16;\n        if( inv_gain_Q16 != psDec->prev_inv_gain_Q16 ) {\n            gain_adj_Q16 =  SKP_DIV32_varQ( inv_gain_Q16, psDec->prev_inv_gain_Q16, 16 );\n        }\n\n        /* Avoid abrupt transition from voiced PLC to unvoiced normal decoding */\n        if( psDec->lossCnt && psDec->prev_sigtype == SIG_TYPE_VOICED &&\n            psDecCtrl->sigtype == SIG_TYPE_UNVOICED && k < ( NB_SUBFR >> 1 ) ) {\n            \n            SKP_memset( B_Q14, 0, LTP_ORDER * sizeof( SKP_int16 ) );\n            B_Q14[ LTP_ORDER/2 ] = ( SKP_int16 )1 << 12; /* 0.25 */\n        \n            sigtype = SIG_TYPE_VOICED;\n            psDecCtrl->pitchL[ k ] = psDec->lagPrev;\n        }\n\n        if( sigtype == SIG_TYPE_VOICED ) {\n            /* Voiced */\n            \n            lag = psDecCtrl->pitchL[ k ];\n            /* Re-whitening */\n            if( ( k & ( 3 - SKP_LSHIFT( NLSF_interpolation_flag, 1 ) ) ) == 0 ) {\n                /* Rewhiten with new A coefs */\n                start_idx = psDec->frame_length - lag - psDec->LPC_order - LTP_ORDER / 2;\n                SKP_assert( start_idx >= 0 );\n                SKP_assert( start_idx <= psDec->frame_length - psDec->LPC_order );\n\n                SKP_memset( FiltState, 0, psDec->LPC_order * sizeof( SKP_int32 ) ); /* Not really necessary, but Valgrind and Coverity will complain otherwise */\n                SKP_Silk_MA_Prediction( &psDec->outBuf[ start_idx + k * ( psDec->frame_length >> 2 ) ], \n                    A_Q12, FiltState, sLTP + start_idx, psDec->frame_length - start_idx, psDec->LPC_order );\n\n                /* After rewhitening the LTP state is unscaled */\n                inv_gain_Q32 = SKP_LSHIFT( inv_gain_Q16, 16 );\n                if( k == 0 ) {\n                    /* Do LTP downscaling */\n                    inv_gain_Q32 = SKP_LSHIFT( SKP_SMULWB( inv_gain_Q32, psDecCtrl->LTP_scale_Q14 ), 2 );\n                }\n                for( i = 0; i < (lag + LTP_ORDER/2); i++ ) {\n                    psDec->sLTP_Q16[ sLTP_buf_idx - i - 1 ] = SKP_SMULWB( inv_gain_Q32, sLTP[ psDec->frame_length - i - 1 ] );\n                }\n            } else {\n                /* Update LTP state when Gain changes */\n                if( gain_adj_Q16 != ( SKP_int32 )1 << 16 ) {\n                    for( i = 0; i < ( lag + LTP_ORDER / 2 ); i++ ) {\n                        psDec->sLTP_Q16[ sLTP_buf_idx - i - 1 ] = SKP_SMULWW( gain_adj_Q16, psDec->sLTP_Q16[ sLTP_buf_idx - i - 1 ] );\n                    }\n                }\n            }\n        }\n        \n        /* Scale short term state */\n        for( i = 0; i < MAX_LPC_ORDER; i++ ) {\n            psDec->sLPC_Q14[ i ] = SKP_SMULWW( gain_adj_Q16, psDec->sLPC_Q14[ i ] );\n        }\n\n        /* Save inv_gain */\n        SKP_assert( inv_gain_Q16 != 0 );\n        psDec->prev_inv_gain_Q16 = inv_gain_Q16;\n\n        /* Long-term prediction */\n        if( sigtype == SIG_TYPE_VOICED ) {\n            /* Setup pointer */\n            pred_lag_ptr = &psDec->sLTP_Q16[ sLTP_buf_idx - lag + LTP_ORDER / 2 ];\n            for( i = 0; i < psDec->subfr_length; i++ ) {\n                /* Unrolled loop */\n                LTP_pred_Q14 = SKP_SMULWB(               pred_lag_ptr[  0 ], B_Q14[ 0 ] );\n                LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -1 ], B_Q14[ 1 ] );\n                LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -2 ], B_Q14[ 2 ] );\n                LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -3 ], B_Q14[ 3 ] );\n                LTP_pred_Q14 = SKP_SMLAWB( LTP_pred_Q14, pred_lag_ptr[ -4 ], B_Q14[ 4 ] );\n                pred_lag_ptr++;\n            \n                /* Generate LPC residual */ \n                pres_Q10[ i ] = SKP_ADD32( pexc_Q10[ i ], SKP_RSHIFT_ROUND( LTP_pred_Q14, 4 ) );\n            \n                /* Update states */\n                psDec->sLTP_Q16[ sLTP_buf_idx ] = SKP_LSHIFT( pres_Q10[ i ], 6 );\n                sLTP_buf_idx++;\n            }\n        } else {\n            SKP_memcpy( pres_Q10, pexc_Q10, psDec->subfr_length * sizeof( SKP_int32 ) );\n        }\n\n\tSKP_Silk_decode_short_term_prediction(vec_Q10, pres_Q10, psDec->sLPC_Q14,A_Q12_tmp,psDec->LPC_order,psDec->subfr_length);\n\n        /* Scale with Gain */\n        for( i = 0; i < psDec->subfr_length; i++ ) {\n            pxq[ i ] = ( SKP_int16 )SKP_SAT16( SKP_RSHIFT_ROUND( SKP_SMULWW( vec_Q10[ i ], Gain_Q16 ), 10 ) );\n        }\n\n        /* Update LPC filter state */\n        SKP_memcpy( psDec->sLPC_Q14, &psDec->sLPC_Q14[ psDec->subfr_length ], MAX_LPC_ORDER * sizeof( SKP_int32 ) );\n        pexc_Q10 += psDec->subfr_length;\n        pres_Q10 += psDec->subfr_length;\n        pxq      += psDec->subfr_length;\n    }\n    \n    /* Copy to output */\n    SKP_memcpy( xq, &psDec->outBuf[ psDec->frame_length ], psDec->frame_length * sizeof( SKP_int16 ) );\n\n}\n\n#if EMBEDDED_ARM<5 \nvoid SKP_Silk_decode_short_term_prediction(\nSKP_int32\t*vec_Q10,\nSKP_int32\t*pres_Q10,\nSKP_int32\t*sLPC_Q14,\nSKP_int16\t*A_Q12_tmp, \nSKP_int\t\tLPC_order,\nSKP_int\t\tsubfr_length\n)\n{\n  SKP_int\ti;\n  SKP_int32\tLPC_pred_Q10;\n  #if !defined(_SYSTEM_IS_BIG_ENDIAN)\n  SKP_int32\tAtmp;\n        /* Short term prediction */\n        /* NOTE: the code below loads two int16 values in an int32, and multiplies each using the   */\n        /* SMLAWB and SMLAWT instructions. On a big-endian CPU the two int16 variables would be     */\n        /* loaded in reverse order and the code will give the wrong result. In that case swapping   */\n        /* the SMLAWB and SMLAWT instructions should solve the problem.                             */\n        if( LPC_order == 16 ) {\n            for( i = 0; i < subfr_length; i++ ) {\n                /* unrolled */\n                Atmp = *( ( SKP_int32* )&A_Q12_tmp[ 0 ] );    /* read two coefficients at once */\n                LPC_pred_Q10 = SKP_SMULWB(               sLPC_Q14[ MAX_LPC_ORDER + i -  1 ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  2 ], Atmp );\n                Atmp = *( ( SKP_int32* )&A_Q12_tmp[ 2 ] );\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  3 ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  4 ], Atmp );\n                Atmp = *( ( SKP_int32* )&A_Q12_tmp[ 4 ] );\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  5 ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  6 ], Atmp );\n                Atmp = *( ( SKP_int32* )&A_Q12_tmp[ 6 ] );\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  7 ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  8 ], Atmp );\n                Atmp = *( ( SKP_int32* )&A_Q12_tmp[ 8 ] );\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  9 ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 10 ], Atmp );\n                Atmp = *( ( SKP_int32* )&A_Q12_tmp[ 10 ] );\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 11 ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 12 ], Atmp );\n                Atmp = *( ( SKP_int32* )&A_Q12_tmp[ 12 ] );\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 13 ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 14 ], Atmp );\n                Atmp = *( ( SKP_int32* )&A_Q12_tmp[ 14 ] );\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 15 ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 16 ], Atmp );\n                \n                /* Add prediction to LPC residual */\n                vec_Q10[ i ] = SKP_ADD32( pres_Q10[ i ], LPC_pred_Q10 );\n                \n                /* Update states */\n                sLPC_Q14[ MAX_LPC_ORDER + i ] = SKP_LSHIFT_ovflw( vec_Q10[ i ], 4 );\n            }\n        } else {\n            SKP_assert( LPC_order == 10 );\n            for( i = 0; i < subfr_length; i++ ) {\n                /* unrolled */\n                Atmp = *( ( SKP_int32* )&A_Q12_tmp[ 0 ] );    /* read two coefficients at once */\n                LPC_pred_Q10 = SKP_SMULWB(               sLPC_Q14[ MAX_LPC_ORDER + i -  1 ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  2 ], Atmp );\n                Atmp = *( ( SKP_int32* )&A_Q12_tmp[ 2 ] );\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  3 ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  4 ], Atmp );\n                Atmp = *( ( SKP_int32* )&A_Q12_tmp[ 4 ] );\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  5 ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  6 ], Atmp );\n                Atmp = *( ( SKP_int32* )&A_Q12_tmp[ 6 ] );\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  7 ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  8 ], Atmp );\n                Atmp = *( ( SKP_int32* )&A_Q12_tmp[ 8 ] );\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  9 ], Atmp );\n                LPC_pred_Q10 = SKP_SMLAWT( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 10 ], Atmp );\n                \n                /* Add prediction to LPC residual */\n                vec_Q10[ i ] = SKP_ADD32( pres_Q10[ i ], LPC_pred_Q10 );\n                \n                /* Update states */\n                sLPC_Q14[ MAX_LPC_ORDER + i ] = SKP_LSHIFT_ovflw( vec_Q10[ i ], 4 );\n            }\n        }\n#else\n    SKP_int j;\n        for( i = 0; i < subfr_length; i++ ) {\n            /* Partially unrolled */\n            LPC_pred_Q10 = SKP_SMULWB(               sLPC_Q14[ MAX_LPC_ORDER + i -  1 ], A_Q12_tmp[ 0 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  2 ], A_Q12_tmp[ 1 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  3 ], A_Q12_tmp[ 2 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  4 ], A_Q12_tmp[ 3 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  5 ], A_Q12_tmp[ 4 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  6 ], A_Q12_tmp[ 5 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  7 ], A_Q12_tmp[ 6 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  8 ], A_Q12_tmp[ 7 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i -  9 ], A_Q12_tmp[ 8 ] );\n            LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - 10 ], A_Q12_tmp[ 9 ] );\n\n            for( j = 10; j < LPC_order; j ++ ) {\n                LPC_pred_Q10 = SKP_SMLAWB( LPC_pred_Q10, sLPC_Q14[ MAX_LPC_ORDER + i - j - 1 ], A_Q12_tmp[ j ] );\n            }\n\n            /* Add prediction to LPC residual */\n            vec_Q10[ i ] = SKP_ADD32( pres_Q10[ i ], LPC_pred_Q10 );\n            \n            /* Update states */\n            sLPC_Q14[ MAX_LPC_ORDER + i ] = SKP_LSHIFT_ovflw( vec_Q10[ i ], 4 );\n        }\n#endif\n}\n#endif\n\n\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_decode_frame.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n\n#include \"SKP_Silk_main.h\"\n#include \"SKP_Silk_PLC.h\"\n\n/****************/\n/* Decode frame */\n/****************/\nSKP_int SKP_Silk_decode_frame(\n    SKP_Silk_decoder_state          *psDec,             /* I/O  Pointer to Silk decoder state               */\n    SKP_int16                       pOut[],             /* O    Pointer to output speech frame              */\n    SKP_int16                       *pN,                /* O    Pointer to size of output frame             */\n    const SKP_uint8                 pCode[],            /* I    Pointer to payload                          */\n    const SKP_int                   nBytes,             /* I    Payload length                              */\n    SKP_int                         action,             /* I    Action from Jitter Buffer                   */\n    SKP_int                         *decBytes           /* O    Used bytes to decode this frame             */\n)\n{\n    SKP_Silk_decoder_control sDecCtrl;\n    SKP_int         L, fs_Khz_old, ret = 0;\n    SKP_int         Pulses[ MAX_FRAME_LENGTH ];\n\n\n    L = psDec->frame_length;\n    sDecCtrl.LTP_scale_Q14 = 0;\n    \n    /* Safety checks */\n    SKP_assert( L > 0 && L <= MAX_FRAME_LENGTH );\n\n    /********************************************/\n    /* Decode Frame if packet is not lost  */\n    /********************************************/\n    *decBytes = 0;\n    if( action == 0 ) {\n        /********************************************/\n        /* Initialize arithmetic coder              */\n        /********************************************/\n        fs_Khz_old    = psDec->fs_kHz;\n        if( psDec->nFramesDecoded == 0 ) {\n            /* Initialize range decoder state */\n            SKP_Silk_range_dec_init( &psDec->sRC, pCode, nBytes );\n        }\n\n        /********************************************/\n        /* Decode parameters and pulse signal       */\n        /********************************************/\n        SKP_Silk_decode_parameters( psDec, &sDecCtrl, Pulses, 1 );\n\n\n        if( psDec->sRC.error ) {\n            psDec->nBytesLeft = 0;\n\n            action              = 1; /* PLC operation */\n            /* revert fs if changed in decode_parameters */\n            SKP_Silk_decoder_set_fs( psDec, fs_Khz_old );\n\n            /* Avoid crashing */\n            *decBytes = psDec->sRC.bufferLength;\n\n            if( psDec->sRC.error == RANGE_CODER_DEC_PAYLOAD_TOO_LONG ) {\n                ret = SKP_SILK_DEC_PAYLOAD_TOO_LARGE;\n            } else {\n                ret = SKP_SILK_DEC_PAYLOAD_ERROR;\n            }\n        } else {\n            *decBytes = psDec->sRC.bufferLength - psDec->nBytesLeft;\n            psDec->nFramesDecoded++;\n        \n            /* Update lengths. Sampling frequency could have changed */\n            L = psDec->frame_length;\n\n            /********************************************************/\n            /* Run inverse NSQ                                      */\n            /********************************************************/\n            SKP_Silk_decode_core( psDec, &sDecCtrl, pOut, Pulses );\n\n            /********************************************************/\n            /* Update PLC state                                     */\n            /********************************************************/\n            SKP_Silk_PLC( psDec, &sDecCtrl, pOut, L, action );\n\n            psDec->lossCnt = 0;\n            psDec->prev_sigtype = sDecCtrl.sigtype;\n\n            /* A frame has been decoded without errors */\n            psDec->first_frame_after_reset = 0;\n        }\n    }\n    /*************************************************************/\n    /* Generate Concealment frame if packet is lost, or corrupt  */\n    /*************************************************************/\n    if( action == 1 ) {\n        /* Handle packet loss by extrapolation */\n        SKP_Silk_PLC( psDec, &sDecCtrl, pOut, L, action );\n    }\n\n    /*************************/\n    /* Update output buffer. */\n    /*************************/\n    SKP_memcpy( psDec->outBuf, pOut, L * sizeof( SKP_int16 ) );\n\n    /****************************************************************/\n    /* Ensure smooth connection of extrapolated and good frames     */\n    /****************************************************************/\n    SKP_Silk_PLC_glue_frames( psDec, &sDecCtrl, pOut, L );\n\n    /************************************************/\n    /* Comfort noise generation / estimation        */\n    /************************************************/\n    SKP_Silk_CNG( psDec, &sDecCtrl, pOut , L );\n\n    /********************************************/\n    /* HP filter output                            */\n    /********************************************/\n    SKP_assert( ( ( psDec->fs_kHz == 12 ) && ( L % 3 ) == 0 ) || \n                ( ( psDec->fs_kHz != 12 ) && ( L % 2 ) == 0 ) );\n    SKP_Silk_biquad( pOut, psDec->HP_B, psDec->HP_A, psDec->HPState, pOut, L );\n\n    /********************************************/\n    /* set output frame length                    */\n    /********************************************/\n    *pN = ( SKP_int16 )L;\n\n    /* Update some decoder state variables */\n    psDec->lagPrev = sDecCtrl.pitchL[ NB_SUBFR - 1 ];\n\n\n    return ret;\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_decode_parameters.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n/* Decode parameters from payload */\nvoid SKP_Silk_decode_parameters(\n    SKP_Silk_decoder_state      *psDec,             /* I/O  State                                       */\n    SKP_Silk_decoder_control    *psDecCtrl,         /* I/O  Decoder control                             */\n    SKP_int                     q[],                /* O    Excitation signal                           */\n    const SKP_int               fullDecoding        /* I    Flag to tell if only arithmetic decoding    */\n)\n{\n    SKP_int   i, k, Ix, fs_kHz_dec, nBytesUsed;\n    SKP_int   Ixs[ NB_SUBFR ];\n    SKP_int   GainsIndices[ NB_SUBFR ];\n    SKP_int   NLSFIndices[ NLSF_MSVQ_MAX_CB_STAGES ];\n    SKP_int   pNLSF_Q15[ MAX_LPC_ORDER ], pNLSF0_Q15[ MAX_LPC_ORDER ];\n    const SKP_int16 *cbk_ptr_Q14;\n    const SKP_Silk_NLSF_CB_struct *psNLSF_CB = NULL;\n    SKP_Silk_range_coder_state  *psRC = &psDec->sRC;\n\n    /************************/\n    /* Decode sampling rate */\n    /************************/\n    /* only done for first frame of packet */\n    if( psDec->nFramesDecoded == 0 ) {\n        SKP_Silk_range_decoder( &Ix, psRC, SKP_Silk_SamplingRates_CDF, SKP_Silk_SamplingRates_offset );\n\n        /* check that sampling rate is supported */\n        if( Ix < 0 || Ix > 3 ) {\n            psRC->error = RANGE_CODER_ILLEGAL_SAMPLING_RATE;\n            return;\n        }\n        fs_kHz_dec = SKP_Silk_SamplingRates_table[ Ix ];\n        SKP_Silk_decoder_set_fs( psDec, fs_kHz_dec );\n    }\n\n    /*******************************************/\n    /* Decode signal type and quantizer offset */\n    /*******************************************/\n    if( psDec->nFramesDecoded == 0 ) {\n        /* first frame in packet: independent coding */\n        SKP_Silk_range_decoder( &Ix, psRC, SKP_Silk_type_offset_CDF, SKP_Silk_type_offset_CDF_offset );\n    } else {\n        /* condidtional coding */\n        SKP_Silk_range_decoder( &Ix, psRC, SKP_Silk_type_offset_joint_CDF[ psDec->typeOffsetPrev ], \n                SKP_Silk_type_offset_CDF_offset );\n    }\n    psDecCtrl->sigtype         = SKP_RSHIFT( Ix, 1 );\n    psDecCtrl->QuantOffsetType = Ix & 1;\n    psDec->typeOffsetPrev      = Ix;\n\n    /****************/\n    /* Decode gains */\n    /****************/\n    /* first subframe */    \n    if( psDec->nFramesDecoded == 0 ) {\n        /* first frame in packet: independent coding */\n        SKP_Silk_range_decoder( &GainsIndices[ 0 ], psRC, SKP_Silk_gain_CDF[ psDecCtrl->sigtype ], SKP_Silk_gain_CDF_offset );\n    } else {\n        /* condidtional coding */\n        SKP_Silk_range_decoder( &GainsIndices[ 0 ], psRC, SKP_Silk_delta_gain_CDF, SKP_Silk_delta_gain_CDF_offset );\n    }\n\n    /* remaining subframes */\n    for( i = 1; i < NB_SUBFR; i++ ) {\n        SKP_Silk_range_decoder( &GainsIndices[ i ], psRC, SKP_Silk_delta_gain_CDF, SKP_Silk_delta_gain_CDF_offset );\n    }\n    \n    /* Dequant Gains */\n    SKP_Silk_gains_dequant( psDecCtrl->Gains_Q16, GainsIndices, &psDec->LastGainIndex, psDec->nFramesDecoded );\n    /****************/\n    /* Decode NLSFs */\n    /****************/\n    /* Set pointer to NLSF VQ CB for the current signal type */\n    psNLSF_CB = psDec->psNLSF_CB[ psDecCtrl->sigtype ];\n\n    /* Range decode NLSF path */\n    SKP_Silk_range_decoder_multi( NLSFIndices, psRC, psNLSF_CB->StartPtr, psNLSF_CB->MiddleIx, psNLSF_CB->nStages );\n\n    /* From the NLSF path, decode an NLSF vector */\n    SKP_Silk_NLSF_MSVQ_decode( pNLSF_Q15, psNLSF_CB, NLSFIndices, psDec->LPC_order );\n\n    /************************************/\n    /* Decode NLSF interpolation factor */\n    /************************************/\n    SKP_Silk_range_decoder( &psDecCtrl->NLSFInterpCoef_Q2, psRC, SKP_Silk_NLSF_interpolation_factor_CDF, \n        SKP_Silk_NLSF_interpolation_factor_offset );\n    \n    /* If just reset, e.g., because internal Fs changed, do not allow interpolation */\n    /* improves the case of packet loss in the first frame after a switch           */\n    if( psDec->first_frame_after_reset == 1 ) {\n        psDecCtrl->NLSFInterpCoef_Q2 = 4;\n    }\n\n    if( fullDecoding ) {\n        /* Convert NLSF parameters to AR prediction filter coefficients */\n        SKP_Silk_NLSF2A_stable( psDecCtrl->PredCoef_Q12[ 1 ], pNLSF_Q15, psDec->LPC_order );\n\n        if( psDecCtrl->NLSFInterpCoef_Q2 < 4 ) {\n            /* Calculation of the interpolated NLSF0 vector from the interpolation factor, */ \n            /* the previous NLSF1, and the current NLSF1                                   */\n            for( i = 0; i < psDec->LPC_order; i++ ) {\n                pNLSF0_Q15[ i ] = psDec->prevNLSF_Q15[ i ] + SKP_RSHIFT( SKP_MUL( psDecCtrl->NLSFInterpCoef_Q2, \n                    ( pNLSF_Q15[ i ] - psDec->prevNLSF_Q15[ i ] ) ), 2 );\n            }\n\n            /* Convert NLSF parameters to AR prediction filter coefficients */\n            SKP_Silk_NLSF2A_stable( psDecCtrl->PredCoef_Q12[ 0 ], pNLSF0_Q15, psDec->LPC_order );\n        } else {\n            /* Copy LPC coefficients for first half from second half */\n            SKP_memcpy( psDecCtrl->PredCoef_Q12[ 0 ], psDecCtrl->PredCoef_Q12[ 1 ], \n                psDec->LPC_order * sizeof( SKP_int16 ) );\n        }\n    }\n\n    SKP_memcpy( psDec->prevNLSF_Q15, pNLSF_Q15, psDec->LPC_order * sizeof( SKP_int ) );\n\n    /* After a packet loss do BWE of LPC coefs */\n    if( psDec->lossCnt ) {\n        SKP_Silk_bwexpander( psDecCtrl->PredCoef_Q12[ 0 ], psDec->LPC_order, BWE_AFTER_LOSS_Q16 );\n        SKP_Silk_bwexpander( psDecCtrl->PredCoef_Q12[ 1 ], psDec->LPC_order, BWE_AFTER_LOSS_Q16 );\n    }\n\n    if( psDecCtrl->sigtype == SIG_TYPE_VOICED ) {\n        /*********************/\n        /* Decode pitch lags */\n        /*********************/\n        /* Get lag index */\n        if( psDec->fs_kHz == 8 ) {\n            SKP_Silk_range_decoder( &Ixs[ 0 ], psRC, SKP_Silk_pitch_lag_NB_CDF,  SKP_Silk_pitch_lag_NB_CDF_offset );\n        } else if( psDec->fs_kHz == 12 ) {\n            SKP_Silk_range_decoder( &Ixs[ 0 ], psRC, SKP_Silk_pitch_lag_MB_CDF,  SKP_Silk_pitch_lag_MB_CDF_offset );\n        } else if( psDec->fs_kHz == 16 ) {\n            SKP_Silk_range_decoder( &Ixs[ 0 ], psRC, SKP_Silk_pitch_lag_WB_CDF,  SKP_Silk_pitch_lag_WB_CDF_offset );\n        } else {\n            SKP_Silk_range_decoder( &Ixs[ 0 ], psRC, SKP_Silk_pitch_lag_SWB_CDF, SKP_Silk_pitch_lag_SWB_CDF_offset );\n        }\n        \n        /* Get countour index */\n        if( psDec->fs_kHz == 8 ) {\n            /* Less codevectors used in 8 khz mode */\n            SKP_Silk_range_decoder( &Ixs[ 1 ], psRC, SKP_Silk_pitch_contour_NB_CDF, SKP_Silk_pitch_contour_NB_CDF_offset );\n        } else {\n            /* Joint for 12, 16, and 24 khz */\n            SKP_Silk_range_decoder( &Ixs[ 1 ], psRC, SKP_Silk_pitch_contour_CDF, SKP_Silk_pitch_contour_CDF_offset );\n        }\n        \n        /* Decode pitch values */\n        SKP_Silk_decode_pitch( Ixs[ 0 ], Ixs[ 1 ], psDecCtrl->pitchL, psDec->fs_kHz );\n\n        /********************/\n        /* Decode LTP gains */\n        /********************/\n        /* Decode PERIndex value */\n        SKP_Silk_range_decoder( &psDecCtrl->PERIndex, psRC, SKP_Silk_LTP_per_index_CDF, \n                SKP_Silk_LTP_per_index_CDF_offset );\n\n        /* Decode Codebook Index */\n        cbk_ptr_Q14 = SKP_Silk_LTP_vq_ptrs_Q14[ psDecCtrl->PERIndex ]; /* set pointer to start of codebook */\n\n        for( k = 0; k < NB_SUBFR; k++ ) {\n            SKP_Silk_range_decoder( &Ix, psRC, SKP_Silk_LTP_gain_CDF_ptrs[ psDecCtrl->PERIndex ], \n                SKP_Silk_LTP_gain_CDF_offsets[ psDecCtrl->PERIndex ] );\n\n            for( i = 0; i < LTP_ORDER; i++ ) {\n                psDecCtrl->LTPCoef_Q14[ k * LTP_ORDER + i ] = cbk_ptr_Q14[ Ix * LTP_ORDER + i ];\n            }\n        }\n\n        /**********************/\n        /* Decode LTP scaling */\n        /**********************/\n        SKP_Silk_range_decoder( &Ix, psRC, SKP_Silk_LTPscale_CDF, SKP_Silk_LTPscale_offset );\n        psDecCtrl->LTP_scale_Q14 = SKP_Silk_LTPScales_table_Q14[ Ix ];\n    } else {\n        SKP_assert( psDecCtrl->sigtype == SIG_TYPE_UNVOICED );\n        SKP_memset( psDecCtrl->pitchL,      0,             NB_SUBFR * sizeof( SKP_int   ) );\n        SKP_memset( psDecCtrl->LTPCoef_Q14, 0, LTP_ORDER * NB_SUBFR * sizeof( SKP_int16 ) );\n        psDecCtrl->PERIndex      = 0;\n        psDecCtrl->LTP_scale_Q14 = 0;\n    }\n\n    /***************/\n    /* Decode seed */\n    /***************/\n    SKP_Silk_range_decoder( &Ix, psRC, SKP_Silk_Seed_CDF, SKP_Silk_Seed_offset );\n    psDecCtrl->Seed = ( SKP_int32 )Ix;\n    /*********************************************/\n    /* Decode quantization indices of excitation */\n    /*********************************************/\n    SKP_Silk_decode_pulses( psRC, psDecCtrl, q, psDec->frame_length );\n\n    /*********************************************/\n    /* Decode VAD flag                           */\n    /*********************************************/\n    SKP_Silk_range_decoder( &psDec->vadFlag, psRC, SKP_Silk_vadflag_CDF, SKP_Silk_vadflag_offset );\n\n    /**************************************/\n    /* Decode Frame termination indicator */\n    /**************************************/\n    SKP_Silk_range_decoder( &psDec->FrameTermination, psRC, SKP_Silk_FrameTermination_CDF, SKP_Silk_FrameTermination_offset );\n\n    /****************************************/\n    /* get number of bytes used so far      */\n    /****************************************/\n    SKP_Silk_range_coder_get_length( psRC, &nBytesUsed );\n    psDec->nBytesLeft = psRC->bufferLength - nBytesUsed;\n    if( psDec->nBytesLeft < 0 ) {\n        psRC->error = RANGE_CODER_READ_BEYOND_BUFFER;\n    }\n\n    /****************************************/\n    /* check remaining bits in last byte    */\n    /****************************************/\n    if( psDec->nBytesLeft == 0 ) {\n        SKP_Silk_range_coder_check_after_decoding( psRC );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_decode_pitch.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/***********************************************************\n* Pitch analyser function\n********************************************************** */\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_common_pitch_est_defines.h\"\n\nvoid SKP_Silk_decode_pitch(\n    SKP_int          lagIndex,                        /* I                             */\n    SKP_int          contourIndex,                    /* O                             */\n    SKP_int          pitch_lags[],                    /* O 4 pitch values              */\n    SKP_int          Fs_kHz                           /* I sampling frequency (kHz)    */\n)\n{\n    SKP_int lag, i, min_lag;\n\n    min_lag = SKP_SMULBB( PITCH_EST_MIN_LAG_MS, Fs_kHz );\n\n    /* Only for 24 / 16 kHz version for now */\n    lag = min_lag + lagIndex;\n    if( Fs_kHz == 8 ) {\n        /* Only a small codebook for 8 khz */\n        for( i = 0; i < PITCH_EST_NB_SUBFR; i++ ) {\n            pitch_lags[ i ] = lag + SKP_Silk_CB_lags_stage2[ i ][ contourIndex ];\n        }\n    } else {\n        for( i = 0; i < PITCH_EST_NB_SUBFR; i++ ) {\n            pitch_lags[ i ] = lag + SKP_Silk_CB_lags_stage3[ i ][ contourIndex ];\n        }\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_decode_pulses.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n/*********************************************/\n/* Decode quantization indices of excitation */\n/*********************************************/\nvoid SKP_Silk_decode_pulses(\n    SKP_Silk_range_coder_state      *psRC,              /* I/O  Range coder state                           */\n    SKP_Silk_decoder_control        *psDecCtrl,         /* I/O  Decoder control                             */\n    SKP_int                         q[],                /* O    Excitation signal                           */\n    const SKP_int                   frame_length        /* I    Frame length (preliminary)                  */\n)\n{\n    SKP_int   i, j, k, iter, abs_q, nLS, bit;\n    SKP_int   sum_pulses[ MAX_NB_SHELL_BLOCKS ], nLshifts[ MAX_NB_SHELL_BLOCKS ];\n    SKP_int   *pulses_ptr;\n    const SKP_uint16 *cdf_ptr;\n    \n    /*********************/\n    /* Decode rate level */\n    /*********************/\n    SKP_Silk_range_decoder( &psDecCtrl->RateLevelIndex, psRC, \n            SKP_Silk_rate_levels_CDF[ psDecCtrl->sigtype ], SKP_Silk_rate_levels_CDF_offset );\n\n    /* Calculate number of shell blocks */\n    iter = frame_length / SHELL_CODEC_FRAME_LENGTH;\n    \n    /***************************************************/\n    /* Sum-Weighted-Pulses Decoding                    */\n    /***************************************************/\n    cdf_ptr = SKP_Silk_pulses_per_block_CDF[ psDecCtrl->RateLevelIndex ];\n    for( i = 0; i < iter; i++ ) {\n        nLshifts[ i ] = 0;\n        SKP_Silk_range_decoder( &sum_pulses[ i ], psRC, cdf_ptr, SKP_Silk_pulses_per_block_CDF_offset );\n\n        /* LSB indication */\n        while( sum_pulses[ i ] == ( MAX_PULSES + 1 ) ) {\n            nLshifts[ i ]++;\n            SKP_Silk_range_decoder( &sum_pulses[ i ], psRC, \n                    SKP_Silk_pulses_per_block_CDF[ N_RATE_LEVELS - 1 ], SKP_Silk_pulses_per_block_CDF_offset );\n        }\n    }\n    \n    /***************************************************/\n    /* Shell decoding                                  */\n    /***************************************************/\n    for( i = 0; i < iter; i++ ) {\n        if( sum_pulses[ i ] > 0 ) {\n            SKP_Silk_shell_decoder( &q[ SKP_SMULBB( i, SHELL_CODEC_FRAME_LENGTH ) ], psRC, sum_pulses[ i ] );\n        } else {\n            SKP_memset( &q[ SKP_SMULBB( i, SHELL_CODEC_FRAME_LENGTH ) ], 0, SHELL_CODEC_FRAME_LENGTH * sizeof( SKP_int ) );\n        }\n    }\n\n    /***************************************************/\n    /* LSB Decoding                                    */\n    /***************************************************/\n    for( i = 0; i < iter; i++ ) {\n        if( nLshifts[ i ] > 0 ) {\n            nLS = nLshifts[ i ];\n            pulses_ptr = &q[ SKP_SMULBB( i, SHELL_CODEC_FRAME_LENGTH ) ];\n            for( k = 0; k < SHELL_CODEC_FRAME_LENGTH; k++ ) {\n                abs_q = pulses_ptr[ k ];\n                for( j = 0; j < nLS; j++ ) {\n                    abs_q = SKP_LSHIFT( abs_q, 1 ); \n                    SKP_Silk_range_decoder( &bit, psRC, SKP_Silk_lsb_CDF, 1 );\n                    abs_q += bit;\n                }\n                pulses_ptr[ k ] = abs_q;\n            }\n        }\n    }\n\n    /****************************************/\n    /* Decode and add signs to pulse signal */\n    /****************************************/\n    SKP_Silk_decode_signs( psRC, q, frame_length, psDecCtrl->sigtype, \n        psDecCtrl->QuantOffsetType, psDecCtrl->RateLevelIndex);\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_decoder_set_fs.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n/* Set decoder sampling rate */\nvoid SKP_Silk_decoder_set_fs(\n    SKP_Silk_decoder_state          *psDec,             /* I/O  Decoder state pointer                       */\n    SKP_int                         fs_kHz              /* I    Sampling frequency (kHz)                    */\n)\n{\n    if( psDec->fs_kHz != fs_kHz ) {\n        psDec->fs_kHz  = fs_kHz;\n        psDec->frame_length = SKP_SMULBB( FRAME_LENGTH_MS, fs_kHz );\n        psDec->subfr_length = SKP_SMULBB( FRAME_LENGTH_MS / NB_SUBFR, fs_kHz );\n        if( psDec->fs_kHz == 8 ) {\n            psDec->LPC_order = MIN_LPC_ORDER;\n            psDec->psNLSF_CB[ 0 ] = &SKP_Silk_NLSF_CB0_10;\n            psDec->psNLSF_CB[ 1 ] = &SKP_Silk_NLSF_CB1_10;\n        } else {\n            psDec->LPC_order = MAX_LPC_ORDER;\n            psDec->psNLSF_CB[ 0 ] = &SKP_Silk_NLSF_CB0_16;\n            psDec->psNLSF_CB[ 1 ] = &SKP_Silk_NLSF_CB1_16;\n        }\n        /* Reset part of the decoder state */\n        SKP_memset( psDec->sLPC_Q14,     0, MAX_LPC_ORDER    * sizeof( SKP_int32 ) );\n        SKP_memset( psDec->outBuf,       0, MAX_FRAME_LENGTH * sizeof( SKP_int16 ) );\n        SKP_memset( psDec->prevNLSF_Q15, 0, MAX_LPC_ORDER    * sizeof( SKP_int )   );\n\n        psDec->lagPrev                 = 100;\n        psDec->LastGainIndex           = 1;\n        psDec->prev_sigtype            = 0;\n        psDec->first_frame_after_reset = 1;\n\n        if( fs_kHz == 24 ) {\n            psDec->HP_A = SKP_Silk_Dec_A_HP_24;\n            psDec->HP_B = SKP_Silk_Dec_B_HP_24;\n        } else if( fs_kHz == 16 ) {\n            psDec->HP_A = SKP_Silk_Dec_A_HP_16;\n            psDec->HP_B = SKP_Silk_Dec_B_HP_16;\n        } else if( fs_kHz == 12 ) {\n            psDec->HP_A = SKP_Silk_Dec_A_HP_12;\n            psDec->HP_B = SKP_Silk_Dec_B_HP_12;\n        } else if( fs_kHz == 8 ) {\n            psDec->HP_A = SKP_Silk_Dec_A_HP_8;\n            psDec->HP_B = SKP_Silk_Dec_B_HP_8;\n        } else {\n            /* unsupported sampling rate */\n            SKP_assert( 0 );\n        }\n    } \n\n    /* Check that settings are valid */\n    SKP_assert( psDec->frame_length > 0 && psDec->frame_length <= MAX_FRAME_LENGTH );\n}\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_detect_SWB_input.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*\n * Detect SWB input by measuring energy above 8 kHz.\n */\n\n#include \"SKP_Silk_main.h\"\n\nvoid SKP_Silk_detect_SWB_input(\n    SKP_Silk_detect_SWB_state   *psSWBdetect,   /* (I/O) encoder state  */\n    const SKP_int16             samplesIn[],    /* (I) input to encoder */\n    SKP_int                     nSamplesIn      /* (I) length of input */\n)\n{\n    SKP_int     HP_8_kHz_len, i, shift;\n    SKP_int16   in_HP_8_kHz[ MAX_FRAME_LENGTH ];\n    SKP_int32   energy_32;\n    \n    /* High pass filter with cutoff at 8 khz */\n    HP_8_kHz_len = SKP_min_int( nSamplesIn, MAX_FRAME_LENGTH );\n    HP_8_kHz_len = SKP_max_int( HP_8_kHz_len, 0 );\n\n    /* Cutoff around 9 khz */\n    /* A = conv(conv([8192,14613, 6868], [8192,12883, 7337]), [8192,11586, 7911]); */\n    /* B = conv(conv([575, -948, 575], [575, -221, 575]), [575, 104, 575]); */\n    SKP_Silk_biquad( samplesIn, SKP_Silk_SWB_detect_B_HP_Q13[ 0 ], SKP_Silk_SWB_detect_A_HP_Q13[ 0 ], \n        psSWBdetect->S_HP_8_kHz[ 0 ], in_HP_8_kHz, HP_8_kHz_len );\n    for( i = 1; i < NB_SOS; i++ ) {\n        SKP_Silk_biquad( in_HP_8_kHz, SKP_Silk_SWB_detect_B_HP_Q13[ i ], SKP_Silk_SWB_detect_A_HP_Q13[ i ], \n            psSWBdetect->S_HP_8_kHz[ i ], in_HP_8_kHz, HP_8_kHz_len );\n    }\n\n    /* Calculate energy in HP signal */\n    SKP_Silk_sum_sqr_shift( &energy_32, &shift, in_HP_8_kHz, HP_8_kHz_len );\n\n    /* Count concecutive samples above threshold, after adjusting threshold for number of input samples and shift */\n    if( energy_32 > SKP_RSHIFT( SKP_SMULBB( HP_8_KHZ_THRES, HP_8_kHz_len ), shift ) ) {\n        psSWBdetect->ConsecSmplsAboveThres += nSamplesIn;\n        if( psSWBdetect->ConsecSmplsAboveThres > CONCEC_SWB_SMPLS_THRES ) {\n            psSWBdetect->SWB_detected = 1;\n        }\n    } else {\n        psSWBdetect->ConsecSmplsAboveThres -= nSamplesIn;\n        psSWBdetect->ConsecSmplsAboveThres = SKP_max( psSWBdetect->ConsecSmplsAboveThres, 0 );\n    }\n\n    /* If sufficient speech activity and no SWB detected, we detect the signal as being WB */\n    if( ( psSWBdetect->ActiveSpeech_ms > WB_DETECT_ACTIVE_SPEECH_MS_THRES ) && ( psSWBdetect->SWB_detected == 0 ) ) {\n        psSWBdetect->WB_detected = 1;\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_div_oabi.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_typedef.h\"\n\nSKP_int32 SKP_DIV32_arm( SKP_int32 a32, SKP_int32 b32 ) {\n\treturn ( ( SKP_int32 )( ( a32 ) / ( b32 ) ) );\n}\n\n\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_enc_API.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n\n#include \"SKP_Silk_define.h\"\n#include \"SKP_Silk_main_FIX.h\"\n#include \"SKP_Silk_SDK_API.h\"\n#include \"SKP_Silk_control.h\"\n#include \"SKP_Silk_typedef.h\"\n#include \"SKP_Silk_structs.h\"\n#define SKP_Silk_EncodeControlStruct SKP_SILK_SDK_EncControlStruct\n\n/****************************************/\n/* Encoder functions                    */\n/****************************************/\n\nSKP_int SKP_Silk_SDK_Get_Encoder_Size( SKP_int32 *encSizeBytes )\n{\n    SKP_int ret = 0;\n    \n    *encSizeBytes = sizeof( SKP_Silk_encoder_state_FIX );\n    \n    return ret;\n}\n\n\n/***************************************/\n/* Read control structure from encoder */\n/***************************************/\nSKP_int SKP_Silk_SDK_QueryEncoder(\n    const void *encState,                       /* I:   State Vector                                    */\n    SKP_Silk_EncodeControlStruct *encStatus     /* O:   Control Structure                               */\n)\n{\n    SKP_Silk_encoder_state_FIX *psEnc;\n    SKP_int ret = 0;\n\n    psEnc = ( SKP_Silk_encoder_state_FIX* )encState;\n\n    encStatus->API_sampleRate        = psEnc->sCmn.API_fs_Hz;\n    encStatus->maxInternalSampleRate = SKP_SMULBB( psEnc->sCmn.maxInternal_fs_kHz, 1000 );\n    encStatus->packetSize            = ( SKP_int )SKP_DIV32_16( psEnc->sCmn.API_fs_Hz * psEnc->sCmn.PacketSize_ms, 1000 );  /* convert samples -> ms */\n    encStatus->bitRate               = psEnc->sCmn.TargetRate_bps;\n    encStatus->packetLossPercentage  = psEnc->sCmn.PacketLoss_perc;\n    encStatus->complexity            = psEnc->sCmn.Complexity;\n    encStatus->useInBandFEC          = psEnc->sCmn.useInBandFEC;\n    encStatus->useDTX                = psEnc->sCmn.useDTX;\n    return ret;\n}\n\n/*************************/\n/* Init or Reset encoder */\n/*************************/\nSKP_int SKP_Silk_SDK_InitEncoder(\n    void                            *encState,          /* I/O: State                                           */\n    SKP_Silk_EncodeControlStruct    *encStatus          /* O:   Control structure                               */\n)\n{\n    SKP_Silk_encoder_state_FIX *psEnc;\n    SKP_int ret = 0;\n\n        \n    psEnc = ( SKP_Silk_encoder_state_FIX* )encState;\n\n    /* Reset Encoder */\n    if( ret += SKP_Silk_init_encoder_FIX( psEnc ) ) {\n        SKP_assert( 0 );\n    }\n\n    /* Read control structure */\n    if( ret += SKP_Silk_SDK_QueryEncoder( encState, encStatus ) ) {\n        SKP_assert( 0 );\n    }\n\n\n    return ret;\n}\n\n/**************************/\n/* Encode frame with Silk */\n/**************************/\nSKP_int SKP_Silk_SDK_Encode( \n    void                                *encState,      /* I/O: State                                           */\n    const SKP_Silk_EncodeControlStruct  *encControl,    /* I:   Control structure                               */\n    const SKP_int16                     *samplesIn,     /* I:   Speech sample input vector                      */\n    SKP_int                             nSamplesIn,     /* I:   Number of samples in input vector               */\n    SKP_uint8                           *outData,       /* O:   Encoded output vector                           */\n    SKP_int16                           *nBytesOut      /* I/O: Number of bytes in outData (input: Max bytes)   */\n)\n{\n    SKP_int   max_internal_fs_kHz, PacketSize_ms, PacketLoss_perc, UseInBandFEC, UseDTX, ret = 0;\n    SKP_int   nSamplesToBuffer, Complexity, input_10ms, nSamplesFromInput = 0;\n    SKP_int32 TargetRate_bps, API_fs_Hz;\n    SKP_int16 MaxBytesOut;\n    SKP_Silk_encoder_state_FIX *psEnc = ( SKP_Silk_encoder_state_FIX* )encState;\n\n    SKP_assert( encControl != NULL );\n\n    /* Check sampling frequency first, to avoid divide by zero later */\n    if( ( ( encControl->API_sampleRate        !=  8000 ) &&\n          ( encControl->API_sampleRate        != 12000 ) &&\n          ( encControl->API_sampleRate        != 16000 ) &&\n          ( encControl->API_sampleRate        != 24000 ) && \n          ( encControl->API_sampleRate        != 32000 ) &&\n          ( encControl->API_sampleRate        != 44100 ) &&\n          ( encControl->API_sampleRate        != 48000 ) ) ||\n        ( ( encControl->maxInternalSampleRate !=  8000 ) &&\n          ( encControl->maxInternalSampleRate != 12000 ) &&\n          ( encControl->maxInternalSampleRate != 16000 ) &&\n          ( encControl->maxInternalSampleRate != 24000 ) ) ) {\n        ret = SKP_SILK_ENC_FS_NOT_SUPPORTED;\n        SKP_assert( 0 );\n        return( ret );\n    }\n\n    /* Set encoder parameters from control structure */\n    API_fs_Hz           =                            encControl->API_sampleRate;\n    max_internal_fs_kHz =                 (SKP_int)( encControl->maxInternalSampleRate >> 10 ) + 1;   /* convert Hz -> kHz */\n    PacketSize_ms       = SKP_DIV32( 1000 * (SKP_int)encControl->packetSize, API_fs_Hz );\n    TargetRate_bps      =                            encControl->bitRate;\n    PacketLoss_perc     =                            encControl->packetLossPercentage;\n    UseInBandFEC        =                            encControl->useInBandFEC;\n    Complexity          =                            encControl->complexity;\n    UseDTX              =                            encControl->useDTX;\n\n    /* Save values in state */\n    psEnc->sCmn.API_fs_Hz          = API_fs_Hz;\n    psEnc->sCmn.maxInternal_fs_kHz = max_internal_fs_kHz;\n    psEnc->sCmn.useInBandFEC       = UseInBandFEC;\n\n    /* Only accept input lengths that are a multiple of 10 ms */\n    input_10ms = SKP_DIV32( 100 * nSamplesIn, API_fs_Hz );\n    if( input_10ms * API_fs_Hz != 100 * nSamplesIn || nSamplesIn < 0 ) {\n        ret = SKP_SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;\n        SKP_assert( 0 );\n        return( ret );\n    }\n\n    TargetRate_bps = SKP_LIMIT( TargetRate_bps, MIN_TARGET_RATE_BPS, MAX_TARGET_RATE_BPS );\n    if( ( ret = SKP_Silk_control_encoder_FIX( psEnc, PacketSize_ms, TargetRate_bps, \n                        PacketLoss_perc, UseDTX, Complexity) ) != 0 ) {\n        SKP_assert( 0 );\n        return( ret );\n    }\n\n    /* Make sure no more than one packet can be produced */\n    if( 1000 * (SKP_int32)nSamplesIn > psEnc->sCmn.PacketSize_ms * API_fs_Hz ) {\n        ret = SKP_SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES;\n        SKP_assert( 0 );\n        return( ret );\n    }\n\n#if MAX_FS_KHZ > 16\n    /* Detect energy above 8 kHz */\n    if( SKP_min( API_fs_Hz, 1000 * max_internal_fs_kHz ) == 24000 && \n            psEnc->sCmn.sSWBdetect.SWB_detected == 0 && \n            psEnc->sCmn.sSWBdetect.WB_detected == 0 ) {\n        SKP_Silk_detect_SWB_input( &psEnc->sCmn.sSWBdetect, samplesIn, ( SKP_int )nSamplesIn );\n    }\n#endif\n\n    /* Input buffering/resampling and encoding */\n    MaxBytesOut = 0;                    /* return 0 output bytes if no encoder called */\n    while( 1 ) {\n        nSamplesToBuffer = psEnc->sCmn.frame_length - psEnc->sCmn.inputBufIx;\n        if( API_fs_Hz == SKP_SMULBB( 1000, psEnc->sCmn.fs_kHz ) ) { \n            nSamplesToBuffer  = SKP_min_int( nSamplesToBuffer, nSamplesIn );\n            nSamplesFromInput = nSamplesToBuffer;\n            /* Copy to buffer */\n            SKP_memcpy( &psEnc->sCmn.inputBuf[ psEnc->sCmn.inputBufIx ], samplesIn, nSamplesFromInput * sizeof( SKP_int16 ) );\n        } else {  \n            nSamplesToBuffer  = SKP_min( nSamplesToBuffer, 10 * input_10ms * psEnc->sCmn.fs_kHz );\n            nSamplesFromInput = SKP_DIV32_16( nSamplesToBuffer * API_fs_Hz, psEnc->sCmn.fs_kHz * 1000 );\n            /* Resample and write to buffer */\n            ret += SKP_Silk_resampler( &psEnc->sCmn.resampler_state, \n                &psEnc->sCmn.inputBuf[ psEnc->sCmn.inputBufIx ], samplesIn, nSamplesFromInput );\n        } \n        samplesIn              += nSamplesFromInput;\n        nSamplesIn             -= nSamplesFromInput;\n        psEnc->sCmn.inputBufIx += nSamplesToBuffer;\n\n        /* Silk encoder */\n        if( psEnc->sCmn.inputBufIx >= psEnc->sCmn.frame_length ) {\n            SKP_assert( psEnc->sCmn.inputBufIx == psEnc->sCmn.frame_length );\n\n            /* Enough data in input buffer, so encode */\n            if( MaxBytesOut == 0 ) {\n                /* No payload obtained so far */\n                MaxBytesOut = *nBytesOut;\n                if( ( ret = SKP_Silk_encode_frame_FIX( psEnc, outData, &MaxBytesOut, psEnc->sCmn.inputBuf ) ) != 0 ) {\n                    SKP_assert( 0 );\n                }\n            } else {\n                /* outData already contains a payload */\n                if( ( ret = SKP_Silk_encode_frame_FIX( psEnc, outData, nBytesOut, psEnc->sCmn.inputBuf ) ) != 0 ) {\n                    SKP_assert( 0 );\n                }\n                /* Check that no second payload was created */\n                SKP_assert( *nBytesOut == 0 );\n            }\n            psEnc->sCmn.inputBufIx = 0;\n            psEnc->sCmn.controlled_since_last_payload = 0;\n\n            if( nSamplesIn == 0 ) {\n                break;\n            }\n        } else {\n            break;\n        }\n    }\n\n    *nBytesOut = MaxBytesOut;\n    if( psEnc->sCmn.useDTX && psEnc->sCmn.inDTX ) {\n        /* DTX simulation */\n        *nBytesOut = 0;\n    }\n\n\n\n    return ret;\n}\n\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_encode_frame_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n#include \"SKP_Silk_tuning_parameters.h\"\n\n/****************/\n/* Encode frame */\n/****************/\nSKP_int SKP_Silk_encode_frame_FIX( \n    SKP_Silk_encoder_state_FIX      *psEnc,             /* I/O  Pointer to Silk FIX encoder state           */\n    SKP_uint8                       *pCode,             /* O    Pointer to payload                          */\n    SKP_int16                       *pnBytesOut,        /* I/O  Pointer to number of payload bytes          */\n                                                        /*      input: max length; output: used             */\n    const SKP_int16                 *pIn                /* I    Pointer to input speech frame               */\n)\n{\n    SKP_Silk_encoder_control_FIX sEncCtrl;\n    SKP_int     nBytes, ret = 0;\n    SKP_int16   *x_frame, *res_pitch_frame;\n    SKP_int16   xfw[ MAX_FRAME_LENGTH ];\n    SKP_int16   pIn_HP[ MAX_FRAME_LENGTH ];\n    SKP_int16   res_pitch[ 2 * MAX_FRAME_LENGTH + LA_PITCH_MAX ];\n    SKP_int     LBRR_idx, frame_terminator, SNR_dB_Q7;\n    const SKP_uint16 *FrameTermination_CDF;\n    /* Low bitrate redundancy parameters */\n    SKP_uint8   LBRRpayload[ MAX_ARITHM_BYTES ];\n    SKP_int16   nBytesLBRR;\n\n\n    sEncCtrl.sCmn.Seed = psEnc->sCmn.frameCounter++ & 3;\n    /**************************************************************/\n    /* Setup Input Pointers, and insert frame in input buffer    */\n    /*************************************************************/\n    x_frame         = psEnc->x_buf + psEnc->sCmn.frame_length; /* start of frame to encode */\n    res_pitch_frame = res_pitch    + psEnc->sCmn.frame_length; /* start of pitch LPC residual frame */\n\n    /****************************/\n    /* Voice Activity Detection */\n    /****************************/\n    ret = SKP_Silk_VAD_GetSA_Q8( &psEnc->sCmn.sVAD, &psEnc->speech_activity_Q8, &SNR_dB_Q7, \n                                 sEncCtrl.input_quality_bands_Q15, &sEncCtrl.input_tilt_Q15,\n                                 pIn,psEnc->sCmn.frame_length );\n\n    /*******************************************/\n    /* High-pass filtering of the input signal */\n    /*******************************************/\n#if HIGH_PASS_INPUT\n    /* Variable high-pass filter */\n    SKP_Silk_HP_variable_cutoff_FIX( psEnc, &sEncCtrl, pIn_HP, pIn );\n#else\n    SKP_memcpy( pIn_HP, pIn, psEnc->sCmn.frame_length * sizeof( SKP_int16 ) );\n#endif\n\n#if SWITCH_TRANSITION_FILTERING\n    /* Ensure smooth bandwidth transitions */\n    SKP_Silk_LP_variable_cutoff( &psEnc->sCmn.sLP, x_frame + LA_SHAPE_MS * psEnc->sCmn.fs_kHz, pIn_HP, psEnc->sCmn.frame_length );\n#else\n    SKP_memcpy( x_frame + LA_SHAPE_MS * psEnc->sCmn.fs_kHz, pIn_HP,psEnc->sCmn.frame_length * sizeof( SKP_int16 ) );\n#endif\n    \n    /*****************************************/\n    /* Find pitch lags, initial LPC analysis */\n    /*****************************************/\n    SKP_Silk_find_pitch_lags_FIX( psEnc, &sEncCtrl, res_pitch, x_frame );\n\n    /************************/\n    /* Noise shape analysis */\n    /************************/\n    SKP_Silk_noise_shape_analysis_FIX( psEnc, &sEncCtrl, res_pitch_frame, x_frame );\n\n    /*****************************************/\n    /* Prefiltering for noise shaper         */\n    /*****************************************/\n    SKP_Silk_prefilter_FIX( psEnc, &sEncCtrl, xfw, x_frame );\n\n    /***************************************************/\n    /* Find linear prediction coefficients (LPC + LTP) */\n    /***************************************************/\n    SKP_Silk_find_pred_coefs_FIX( psEnc, &sEncCtrl, res_pitch );\n\n    /****************************************/\n    /* Process gains                        */\n    /****************************************/\n    SKP_Silk_process_gains_FIX( psEnc, &sEncCtrl );\n    \n    \n    /****************************************/\n    /* Low Bitrate Redundant Encoding       */\n    /****************************************/\n    nBytesLBRR = MAX_ARITHM_BYTES;\n    SKP_Silk_LBRR_encode_FIX( psEnc, &sEncCtrl, LBRRpayload, &nBytesLBRR, xfw );\n\n    /*****************************************/\n    /* Noise shaping quantization            */\n    /*****************************************/\n    if( psEnc->sCmn.nStatesDelayedDecision > 1 || psEnc->sCmn.warping_Q16 > 0 ) {\n        SKP_Silk_NSQ_del_dec( &psEnc->sCmn, &sEncCtrl.sCmn, &psEnc->sCmn.sNSQ, xfw,\n            psEnc->sCmn.q, sEncCtrl.sCmn.NLSFInterpCoef_Q2, \n            sEncCtrl.PredCoef_Q12[ 0 ], sEncCtrl.LTPCoef_Q14, sEncCtrl.AR2_Q13, sEncCtrl.HarmShapeGain_Q14, \n            sEncCtrl.Tilt_Q14, sEncCtrl.LF_shp_Q14, sEncCtrl.Gains_Q16, sEncCtrl.Lambda_Q10, \n            sEncCtrl.LTP_scale_Q14 );\n    } else {\n        SKP_Silk_NSQ( &psEnc->sCmn, &sEncCtrl.sCmn, &psEnc->sCmn.sNSQ, xfw, \n            psEnc->sCmn.q, sEncCtrl.sCmn.NLSFInterpCoef_Q2, \n            sEncCtrl.PredCoef_Q12[ 0 ], sEncCtrl.LTPCoef_Q14, sEncCtrl.AR2_Q13, sEncCtrl.HarmShapeGain_Q14, \n            sEncCtrl.Tilt_Q14, sEncCtrl.LF_shp_Q14, sEncCtrl.Gains_Q16, sEncCtrl.Lambda_Q10, \n            sEncCtrl.LTP_scale_Q14 );\n    }\n\n    /**************************************************/\n    /* Convert speech activity into VAD and DTX flags */\n    /**************************************************/\n    if( psEnc->speech_activity_Q8 < SKP_FIX_CONST( SPEECH_ACTIVITY_DTX_THRES, 8 ) ) {\n        psEnc->sCmn.vadFlag = NO_VOICE_ACTIVITY;\n        psEnc->sCmn.noSpeechCounter++;\n        if( psEnc->sCmn.noSpeechCounter > NO_SPEECH_FRAMES_BEFORE_DTX ) {\n            psEnc->sCmn.inDTX = 1;\n        }\n        if( psEnc->sCmn.noSpeechCounter > MAX_CONSECUTIVE_DTX + NO_SPEECH_FRAMES_BEFORE_DTX ) {\n            psEnc->sCmn.noSpeechCounter = NO_SPEECH_FRAMES_BEFORE_DTX;\n            psEnc->sCmn.inDTX           = 0;\n        }\n    } else {\n        psEnc->sCmn.noSpeechCounter = 0;\n        psEnc->sCmn.inDTX           = 0;\n        psEnc->sCmn.vadFlag         = VOICE_ACTIVITY;\n    }\n\n    /****************************************/\n    /* Initialize range coder               */\n    /****************************************/\n    if( psEnc->sCmn.nFramesInPayloadBuf == 0 ) {\n        SKP_Silk_range_enc_init( &psEnc->sCmn.sRC );\n        psEnc->sCmn.nBytesInPayloadBuf = 0;\n    }\n\n    /****************************************/\n    /* Encode Parameters                    */\n    /****************************************/\n    SKP_Silk_encode_parameters( &psEnc->sCmn, &sEncCtrl.sCmn, &psEnc->sCmn.sRC, psEnc->sCmn.q );\n    FrameTermination_CDF = SKP_Silk_FrameTermination_CDF;\n\n    /****************************************/\n    /* Update Buffers and State             */\n    /****************************************/\n    /* Update input buffer */\n    SKP_memmove( psEnc->x_buf, &psEnc->x_buf[ psEnc->sCmn.frame_length ], \n        ( psEnc->sCmn.frame_length + LA_SHAPE_MS * psEnc->sCmn.fs_kHz ) * sizeof( SKP_int16 ) );\n    \n    /* Parameters needed for next frame */\n    psEnc->sCmn.prev_sigtype            = sEncCtrl.sCmn.sigtype;\n    psEnc->sCmn.prevLag                 = sEncCtrl.sCmn.pitchL[ NB_SUBFR - 1];\n    psEnc->sCmn.first_frame_after_reset = 0;\n\n    if( psEnc->sCmn.sRC.error ) {\n        /* Encoder returned error: clear payload buffer */\n        psEnc->sCmn.nFramesInPayloadBuf = 0;\n    } else {\n        psEnc->sCmn.nFramesInPayloadBuf++;\n    }\n\n    /****************************************/\n    /* Finalize payload and copy to output  */\n    /****************************************/\n    if( psEnc->sCmn.nFramesInPayloadBuf * FRAME_LENGTH_MS >= psEnc->sCmn.PacketSize_ms ) {\n\n        LBRR_idx = ( psEnc->sCmn.oldest_LBRR_idx + 1 ) & LBRR_IDX_MASK;\n\n        /* Check if FEC information should be added */\n        frame_terminator = SKP_SILK_LAST_FRAME;\n        if( psEnc->sCmn.LBRR_buffer[ LBRR_idx ].usage == SKP_SILK_ADD_LBRR_TO_PLUS1 ) {\n            frame_terminator = SKP_SILK_LBRR_VER1;\n        }\n        if( psEnc->sCmn.LBRR_buffer[ psEnc->sCmn.oldest_LBRR_idx ].usage == SKP_SILK_ADD_LBRR_TO_PLUS2 ) {\n            frame_terminator = SKP_SILK_LBRR_VER2;\n            LBRR_idx = psEnc->sCmn.oldest_LBRR_idx;\n        }\n\n        /* Add the frame termination info to stream */\n        SKP_Silk_range_encoder( &psEnc->sCmn.sRC, frame_terminator, FrameTermination_CDF );\n\n        /* Payload length so far */\n        SKP_Silk_range_coder_get_length( &psEnc->sCmn.sRC, &nBytes );\n\n        /* Check that there is enough space in external output buffer, and move data */\n        if( *pnBytesOut >= nBytes ) {\n            SKP_Silk_range_enc_wrap_up( &psEnc->sCmn.sRC );\n            SKP_memcpy( pCode, psEnc->sCmn.sRC.buffer, nBytes * sizeof( SKP_uint8 ) );\n            \n            if( frame_terminator > SKP_SILK_MORE_FRAMES && \n                    *pnBytesOut >= nBytes + psEnc->sCmn.LBRR_buffer[ LBRR_idx ].nBytes ) {\n                /* Get old packet and add to payload. */\n                SKP_memcpy( &pCode[ nBytes ],\n                    psEnc->sCmn.LBRR_buffer[ LBRR_idx ].payload,\n                    psEnc->sCmn.LBRR_buffer[ LBRR_idx ].nBytes * sizeof( SKP_uint8 ) );\n                nBytes += psEnc->sCmn.LBRR_buffer[ LBRR_idx ].nBytes;\n            }\n\n            *pnBytesOut = nBytes;\n\n            /* Update FEC buffer */\n            SKP_memcpy( psEnc->sCmn.LBRR_buffer[ psEnc->sCmn.oldest_LBRR_idx ].payload, LBRRpayload, \n                nBytesLBRR * sizeof( SKP_uint8 ) );\n            psEnc->sCmn.LBRR_buffer[ psEnc->sCmn.oldest_LBRR_idx ].nBytes = nBytesLBRR;\n            /* The line below describes how FEC should be used */\n            psEnc->sCmn.LBRR_buffer[ psEnc->sCmn.oldest_LBRR_idx ].usage = sEncCtrl.sCmn.LBRR_usage;\n            psEnc->sCmn.oldest_LBRR_idx = ( psEnc->sCmn.oldest_LBRR_idx + 1 ) & LBRR_IDX_MASK;\n\n        } else {\n            /* Not enough space: Payload will be discarded */\n            *pnBytesOut = 0;\n            nBytes      = 0;\n            ret = SKP_SILK_ENC_PAYLOAD_BUF_TOO_SHORT;\n        }\n\n        /* Reset the number of frames in payload buffer */\n        psEnc->sCmn.nFramesInPayloadBuf = 0;\n    } else {\n        /* No payload this time */\n        *pnBytesOut = 0;\n\n        /* Encode that more frames follows */\n        frame_terminator = SKP_SILK_MORE_FRAMES;\n        SKP_Silk_range_encoder( &psEnc->sCmn.sRC, frame_terminator, FrameTermination_CDF );\n\n        /* Payload length so far */\n        SKP_Silk_range_coder_get_length( &psEnc->sCmn.sRC, &nBytes );\n        \n    }\n\n    /* Check for arithmetic coder errors */\n    if( psEnc->sCmn.sRC.error ) {\n        ret = SKP_SILK_ENC_INTERNAL_ERROR;\n    }\n\n    /* Simulate number of ms buffered in channel because of exceeding TargetRate */\n    SKP_assert(  ( 8 * 1000 * ( (SKP_int64)nBytes - (SKP_int64)psEnc->sCmn.nBytesInPayloadBuf ) ) == \n        SKP_SAT32( 8 * 1000 * ( (SKP_int64)nBytes - (SKP_int64)psEnc->sCmn.nBytesInPayloadBuf ) ) );\n    SKP_assert( psEnc->sCmn.TargetRate_bps > 0 );\n    psEnc->BufferedInChannel_ms   += SKP_DIV32( 8 * 1000 * ( nBytes - psEnc->sCmn.nBytesInPayloadBuf ), psEnc->sCmn.TargetRate_bps );\n    psEnc->BufferedInChannel_ms   -= FRAME_LENGTH_MS;\n    psEnc->BufferedInChannel_ms    = SKP_LIMIT_int( psEnc->BufferedInChannel_ms, 0, 100 );\n    psEnc->sCmn.nBytesInPayloadBuf = nBytes;\n\n    if( psEnc->speech_activity_Q8 > SKP_FIX_CONST( WB_DETECT_ACTIVE_SPEECH_LEVEL_THRES, 8 ) ) {\n        psEnc->sCmn.sSWBdetect.ActiveSpeech_ms = SKP_ADD_POS_SAT32( psEnc->sCmn.sSWBdetect.ActiveSpeech_ms, FRAME_LENGTH_MS ); \n    }\n\n\n    return( ret );\n}\n\n/* Low BitRate Redundancy encoding functionality. Reuse all parameters but encode residual with lower bitrate */\nvoid SKP_Silk_LBRR_encode_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,         /* I/O  Pointer to Silk encoder state           */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl,     /* I/O  Pointer to Silk encoder control struct  */\n    SKP_uint8                       *pCode,         /* O    Pointer to payload                      */\n    SKP_int16                       *pnBytesOut,    /* I/O  Pointer to number of payload bytes      */\n    SKP_int16                       xfw[]           /* I    Input signal                            */\n)\n{\n    SKP_int     TempGainsIndices[ NB_SUBFR ], frame_terminator;\n    SKP_int     nBytes, nFramesInPayloadBuf;\n    SKP_int32   TempGains_Q16[ NB_SUBFR ];\n    SKP_int     typeOffset, LTP_scaleIndex, Rate_only_parameters = 0;\n    /*******************************************/\n    /* Control use of inband LBRR              */\n    /*******************************************/\n    SKP_Silk_LBRR_ctrl_FIX( psEnc, &psEncCtrl->sCmn );\n\n    if( psEnc->sCmn.LBRR_enabled ) {\n        /* Save original gains */\n        SKP_memcpy( TempGainsIndices, psEncCtrl->sCmn.GainsIndices, NB_SUBFR * sizeof( SKP_int   ) );\n        SKP_memcpy( TempGains_Q16,    psEncCtrl->Gains_Q16,         NB_SUBFR * sizeof( SKP_int32 ) );\n\n        typeOffset     = psEnc->sCmn.typeOffsetPrev; // Temp save as cannot be overwritten\n        LTP_scaleIndex = psEncCtrl->sCmn.LTP_scaleIndex;\n\n        /* Set max rate where quant signal is encoded */\n        if( psEnc->sCmn.fs_kHz == 8 ) {\n            Rate_only_parameters = 13500;\n        } else if( psEnc->sCmn.fs_kHz == 12 ) {\n            Rate_only_parameters = 15500;\n        } else if( psEnc->sCmn.fs_kHz == 16 ) {\n            Rate_only_parameters = 17500;\n        } else if( psEnc->sCmn.fs_kHz == 24 ) {\n            Rate_only_parameters = 19500;\n        } else {\n            SKP_assert( 0 );\n        }\n\n        if( psEnc->sCmn.Complexity > 0 && psEnc->sCmn.TargetRate_bps > Rate_only_parameters ) {\n            if( psEnc->sCmn.nFramesInPayloadBuf == 0 ) {\n                /* First frame in packet; copy everything */\n                SKP_memcpy( &psEnc->sCmn.sNSQ_LBRR, &psEnc->sCmn.sNSQ, sizeof( SKP_Silk_nsq_state ) );\n\n                psEnc->sCmn.LBRRprevLastGainIndex = psEnc->sShape.LastGainIndex;\n                /* Increase Gains to get target LBRR rate */\n                psEncCtrl->sCmn.GainsIndices[ 0 ] = psEncCtrl->sCmn.GainsIndices[ 0 ] + psEnc->sCmn.LBRR_GainIncreases;\n                psEncCtrl->sCmn.GainsIndices[ 0 ] = SKP_LIMIT_int( psEncCtrl->sCmn.GainsIndices[ 0 ], 0, N_LEVELS_QGAIN - 1 );\n            }\n            /* Decode to get gains in sync with decoder         */\n            /* Overwrite unquantized gains with quantized gains */\n            SKP_Silk_gains_dequant( psEncCtrl->Gains_Q16, psEncCtrl->sCmn.GainsIndices, \n                &psEnc->sCmn.LBRRprevLastGainIndex, psEnc->sCmn.nFramesInPayloadBuf );\n\n            /*****************************************/\n            /* Noise shaping quantization            */\n            /*****************************************/\n            if( psEnc->sCmn.nStatesDelayedDecision > 1 || psEnc->sCmn.warping_Q16 > 0 ) {\n                SKP_Silk_NSQ_del_dec( &psEnc->sCmn, &psEncCtrl->sCmn, &psEnc->sCmn.sNSQ_LBRR, xfw, psEnc->sCmn.q_LBRR, \n                    psEncCtrl->sCmn.NLSFInterpCoef_Q2, psEncCtrl->PredCoef_Q12[ 0 ], psEncCtrl->LTPCoef_Q14, \n                    psEncCtrl->AR2_Q13, psEncCtrl->HarmShapeGain_Q14, psEncCtrl->Tilt_Q14, psEncCtrl->LF_shp_Q14, \n                    psEncCtrl->Gains_Q16, psEncCtrl->Lambda_Q10, psEncCtrl->LTP_scale_Q14 );\n            } else {\n                SKP_Silk_NSQ( &psEnc->sCmn, &psEncCtrl->sCmn, &psEnc->sCmn.sNSQ_LBRR, xfw, psEnc->sCmn.q_LBRR, \n                    psEncCtrl->sCmn.NLSFInterpCoef_Q2, psEncCtrl->PredCoef_Q12[ 0 ], psEncCtrl->LTPCoef_Q14, \n                    psEncCtrl->AR2_Q13, psEncCtrl->HarmShapeGain_Q14, psEncCtrl->Tilt_Q14, psEncCtrl->LF_shp_Q14, \n                    psEncCtrl->Gains_Q16, psEncCtrl->Lambda_Q10, psEncCtrl->LTP_scale_Q14 );\n            }\n        } else {\n            SKP_memset( psEnc->sCmn.q_LBRR, 0, psEnc->sCmn.frame_length * sizeof( SKP_int8 ) );\n            psEncCtrl->sCmn.LTP_scaleIndex = 0;\n        }\n        /****************************************/\n        /* Initialize arithmetic coder          */\n        /****************************************/\n        if( psEnc->sCmn.nFramesInPayloadBuf == 0 ) {\n            SKP_Silk_range_enc_init( &psEnc->sCmn.sRC_LBRR );\n            psEnc->sCmn.nBytesInPayloadBuf = 0;\n        }\n\n        /****************************************/\n        /* Encode Parameters                    */\n        /****************************************/\n        SKP_Silk_encode_parameters( &psEnc->sCmn, &psEncCtrl->sCmn, \n            &psEnc->sCmn.sRC_LBRR, psEnc->sCmn.q_LBRR );\n\n        if( psEnc->sCmn.sRC_LBRR.error ) {\n            /* Encoder returned error: clear payload buffer */\n            nFramesInPayloadBuf = 0;\n        } else {\n            nFramesInPayloadBuf = psEnc->sCmn.nFramesInPayloadBuf + 1;\n        }\n\n        /****************************************/\n        /* Finalize payload and copy to output  */\n        /****************************************/\n        if( SKP_SMULBB( nFramesInPayloadBuf, FRAME_LENGTH_MS ) >= psEnc->sCmn.PacketSize_ms ) {\n\n            /* Check if FEC information should be added */\n            frame_terminator = SKP_SILK_LAST_FRAME;\n\n            /* Add the frame termination info to stream */\n            SKP_Silk_range_encoder( &psEnc->sCmn.sRC_LBRR, frame_terminator, SKP_Silk_FrameTermination_CDF );\n\n            /* Payload length so far */\n            SKP_Silk_range_coder_get_length( &psEnc->sCmn.sRC_LBRR, &nBytes );\n\n            /* Check that there is enough space in external output buffer and move data */\n            if( *pnBytesOut >= nBytes ) {\n                SKP_Silk_range_enc_wrap_up( &psEnc->sCmn.sRC_LBRR );\n                SKP_memcpy( pCode, psEnc->sCmn.sRC_LBRR.buffer, nBytes * sizeof( SKP_uint8 ) );\n\n                *pnBytesOut = nBytes;\n            } else {\n                /* Not enough space: payload will be discarded */\n                *pnBytesOut = 0;\n                SKP_assert( 0 );\n            }\n        } else {\n            /* No payload this time */\n            *pnBytesOut = 0;\n\n            /* Encode that more frames follows */\n            frame_terminator = SKP_SILK_MORE_FRAMES;\n            SKP_Silk_range_encoder( &psEnc->sCmn.sRC_LBRR, frame_terminator, SKP_Silk_FrameTermination_CDF );\n        }\n\n        /* Restore original Gains */\n        SKP_memcpy( psEncCtrl->sCmn.GainsIndices, TempGainsIndices, NB_SUBFR * sizeof( SKP_int   ) );\n        SKP_memcpy( psEncCtrl->Gains_Q16,         TempGains_Q16,    NB_SUBFR * sizeof( SKP_int32 ) );\n    \n        /* Restore LTP scale index and typeoffset */\n        psEncCtrl->sCmn.LTP_scaleIndex = LTP_scaleIndex;\n        psEnc->sCmn.typeOffsetPrev = typeOffset;\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_encode_parameters.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n/*******************************************/\n/* Encode parameters to create the payload */\n/*******************************************/\nvoid SKP_Silk_encode_parameters(\n    SKP_Silk_encoder_state          *psEncC,        /* I/O  Encoder state                   */\n    SKP_Silk_encoder_control        *psEncCtrlC,    /* I/O  Encoder control                 */\n    SKP_Silk_range_coder_state      *psRC,          /* I/O  Range encoder state             */\n    const SKP_int8                  *q              /* I    Quantization indices            */\n)\n{\n    SKP_int   i, k, typeOffset;\n    const SKP_Silk_NLSF_CB_struct *psNLSF_CB;\n\n\n    /************************/\n    /* Encode sampling rate */\n    /************************/\n    /* only done for first frame in packet */\n    if( psEncC->nFramesInPayloadBuf == 0 ) {\n        /* get sampling rate index */\n        for( i = 0; i < 3; i++ ) {\n            if( SKP_Silk_SamplingRates_table[ i ] == psEncC->fs_kHz ) {\n                break;\n            }\n        }\n        SKP_Silk_range_encoder( psRC, i, SKP_Silk_SamplingRates_CDF );\n    }\n\n    /*******************************************/\n    /* Encode signal type and quantizer offset */\n    /*******************************************/\n    typeOffset = 2 * psEncCtrlC->sigtype + psEncCtrlC->QuantOffsetType;\n    if( psEncC->nFramesInPayloadBuf == 0 ) {\n        /* first frame in packet: independent coding */\n        SKP_Silk_range_encoder( psRC, typeOffset, SKP_Silk_type_offset_CDF );\n    } else {\n        /* condidtional coding */\n        SKP_Silk_range_encoder( psRC, typeOffset, SKP_Silk_type_offset_joint_CDF[ psEncC->typeOffsetPrev ] );\n    }\n    psEncC->typeOffsetPrev = typeOffset;\n\n    /****************/\n    /* Encode gains */\n    /****************/\n    /* first subframe */\n    if( psEncC->nFramesInPayloadBuf == 0 ) {\n        /* first frame in packet: independent coding */\n        SKP_Silk_range_encoder( psRC, psEncCtrlC->GainsIndices[ 0 ], SKP_Silk_gain_CDF[ psEncCtrlC->sigtype ] );\n    } else {\n        /* condidtional coding */\n        SKP_Silk_range_encoder( psRC, psEncCtrlC->GainsIndices[ 0 ], SKP_Silk_delta_gain_CDF );\n    }\n\n    /* remaining subframes */\n    for( i = 1; i < NB_SUBFR; i++ ) {\n        SKP_Silk_range_encoder( psRC, psEncCtrlC->GainsIndices[ i ], SKP_Silk_delta_gain_CDF );\n    }\n\n\n    /****************/\n    /* Encode NLSFs */\n    /****************/\n    /* Range encoding of the NLSF path */\n    psNLSF_CB = psEncC->psNLSF_CB[ psEncCtrlC->sigtype ];\n    SKP_Silk_range_encoder_multi( psRC, psEncCtrlC->NLSFIndices, psNLSF_CB->StartPtr, psNLSF_CB->nStages );\n\n    /* Encode NLSF interpolation factor */\n    SKP_assert( psEncC->useInterpolatedNLSFs == 1 || psEncCtrlC->NLSFInterpCoef_Q2 == ( 1 << 2 ) );\n    SKP_Silk_range_encoder( psRC, psEncCtrlC->NLSFInterpCoef_Q2, SKP_Silk_NLSF_interpolation_factor_CDF );\n\n\n    if( psEncCtrlC->sigtype == SIG_TYPE_VOICED ) {\n        /*********************/\n        /* Encode pitch lags */\n        /*********************/\n\n\n        /* lag index */\n        if( psEncC->fs_kHz == 8 ) {\n            SKP_Silk_range_encoder( psRC, psEncCtrlC->lagIndex, SKP_Silk_pitch_lag_NB_CDF );\n        } else if( psEncC->fs_kHz == 12 ) {\n            SKP_Silk_range_encoder( psRC, psEncCtrlC->lagIndex, SKP_Silk_pitch_lag_MB_CDF );\n        } else if( psEncC->fs_kHz == 16 ) {\n            SKP_Silk_range_encoder( psRC, psEncCtrlC->lagIndex, SKP_Silk_pitch_lag_WB_CDF );\n        } else {\n            SKP_Silk_range_encoder( psRC, psEncCtrlC->lagIndex, SKP_Silk_pitch_lag_SWB_CDF );\n        }\n\n\n        /* countour index */\n        if( psEncC->fs_kHz == 8 ) {\n            /* Less codevectors used in 8 khz mode */\n            SKP_Silk_range_encoder( psRC, psEncCtrlC->contourIndex, SKP_Silk_pitch_contour_NB_CDF );\n        } else {\n            /* Joint for 12, 16, 24 khz */\n            SKP_Silk_range_encoder( psRC, psEncCtrlC->contourIndex, SKP_Silk_pitch_contour_CDF );\n        }\n\n        /********************/\n        /* Encode LTP gains */\n        /********************/\n\n        /* PERIndex value */\n        SKP_Silk_range_encoder( psRC, psEncCtrlC->PERIndex, SKP_Silk_LTP_per_index_CDF );\n\n        /* Codebook Indices */\n        for( k = 0; k < NB_SUBFR; k++ ) {\n            SKP_Silk_range_encoder( psRC, psEncCtrlC->LTPIndex[ k ], SKP_Silk_LTP_gain_CDF_ptrs[ psEncCtrlC->PERIndex ] );\n        }\n\n        /**********************/\n        /* Encode LTP scaling */\n        /**********************/\n        SKP_Silk_range_encoder( psRC, psEncCtrlC->LTP_scaleIndex, SKP_Silk_LTPscale_CDF );\n    }\n\n\n    /***************/\n    /* Encode seed */\n    /***************/\n    SKP_Silk_range_encoder( psRC, psEncCtrlC->Seed, SKP_Silk_Seed_CDF );\n\n    /*********************************************/\n    /* Encode quantization indices of excitation */\n    /*********************************************/\n    SKP_Silk_encode_pulses( psRC, psEncCtrlC->sigtype, psEncCtrlC->QuantOffsetType, q, psEncC->frame_length );\n\n\n    /*********************************************/\n    /* Encode VAD flag                           */\n    /*********************************************/\n    SKP_Silk_range_encoder( psRC, psEncC->vadFlag, SKP_Silk_vadflag_CDF );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_encode_pulses.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n/*********************************************/\n/* Encode quantization indices of excitation */\n/*********************************************/\n\nSKP_INLINE SKP_int combine_and_check(       /* return ok */\n    SKP_int         *pulses_comb,           /* O */\n    const SKP_int   *pulses_in,             /* I */\n    SKP_int         max_pulses,             /* I    max value for sum of pulses */\n    SKP_int         len                     /* I    number of output values */\n) \n{\n    SKP_int k, sum;\n\n    for( k = 0; k < len; k++ ) {\n        sum = pulses_in[ 2 * k ] + pulses_in[ 2 * k + 1 ];\n        if( sum > max_pulses ) {\n            return 1;\n        }\n        pulses_comb[ k ] = sum;\n    }\n\n    return 0;\n}\n\n/* Encode quantization indices of excitation */\nvoid SKP_Silk_encode_pulses(\n    SKP_Silk_range_coder_state      *psRC,          /* I/O  Range coder state               */\n    const SKP_int                   sigtype,        /* I    Sigtype                         */\n    const SKP_int                   QuantOffsetType,/* I    QuantOffsetType                 */\n    const SKP_int8                  q[],            /* I    quantization indices            */\n    const SKP_int                   frame_length    /* I    Frame length                    */\n)\n{\n    SKP_int   i, k, j, iter, bit, nLS, scale_down, RateLevelIndex = 0;\n    SKP_int32 abs_q, minSumBits_Q6, sumBits_Q6;\n    SKP_int   abs_pulses[ MAX_FRAME_LENGTH ];\n    SKP_int   sum_pulses[ MAX_NB_SHELL_BLOCKS ];\n    SKP_int   nRshifts[   MAX_NB_SHELL_BLOCKS ];\n    SKP_int   pulses_comb[ 8 ];\n    SKP_int   *abs_pulses_ptr;\n    const SKP_int8 *pulses_ptr;\n    const SKP_uint16 *cdf_ptr;\n    const SKP_int16 *nBits_ptr;\n\n    SKP_memset( pulses_comb, 0, 8 * sizeof( SKP_int ) ); // Fixing Valgrind reported problem\n\n    /****************************/\n    /* Prepare for shell coding */\n    /****************************/\n    /* Calculate number of shell blocks */\n    iter = frame_length / SHELL_CODEC_FRAME_LENGTH;\n    \n    /* Take the absolute value of the pulses */\n    for( i = 0; i < frame_length; i+=4 ) {\n        abs_pulses[i+0] = ( SKP_int )SKP_abs( q[ i + 0 ] );\n        abs_pulses[i+1] = ( SKP_int )SKP_abs( q[ i + 1 ] );\n        abs_pulses[i+2] = ( SKP_int )SKP_abs( q[ i + 2 ] );\n        abs_pulses[i+3] = ( SKP_int )SKP_abs( q[ i + 3 ] );\n    }\n\n    /* Calc sum pulses per shell code frame */\n    abs_pulses_ptr = abs_pulses;\n    for( i = 0; i < iter; i++ ) {\n        nRshifts[ i ] = 0;\n\n        while( 1 ) {\n            /* 1+1 -> 2 */\n            scale_down = combine_and_check( pulses_comb, abs_pulses_ptr, SKP_Silk_max_pulses_table[ 0 ], 8 );\n\n            /* 2+2 -> 4 */\n            scale_down += combine_and_check( pulses_comb, pulses_comb, SKP_Silk_max_pulses_table[ 1 ], 4 );\n\n            /* 4+4 -> 8 */\n            scale_down += combine_and_check( pulses_comb, pulses_comb, SKP_Silk_max_pulses_table[ 2 ], 2 );\n\n            /* 8+8 -> 16 */\n            sum_pulses[ i ] = pulses_comb[ 0 ] + pulses_comb[ 1 ];\n            if( sum_pulses[ i ] > SKP_Silk_max_pulses_table[ 3 ] ) {\n                scale_down++;\n            }\n\n            if( scale_down ) {\n                /* We need to down scale the quantization signal */\n                nRshifts[ i ]++;                \n                for( k = 0; k < SHELL_CODEC_FRAME_LENGTH; k++ ) {\n                    abs_pulses_ptr[ k ] = SKP_RSHIFT( abs_pulses_ptr[ k ], 1 );\n                }\n            } else {\n                /* Jump out of while(1) loop and go to next shell coding frame */\n                break;\n            }\n        }\n        abs_pulses_ptr += SHELL_CODEC_FRAME_LENGTH;\n    }\n\n    /**************/\n    /* Rate level */\n    /**************/\n    /* find rate level that leads to fewest bits for coding of pulses per block info */\n    minSumBits_Q6 = SKP_int32_MAX;\n    for( k = 0; k < N_RATE_LEVELS - 1; k++ ) {\n        nBits_ptr  = SKP_Silk_pulses_per_block_BITS_Q6[ k ];\n        sumBits_Q6 = SKP_Silk_rate_levels_BITS_Q6[sigtype][ k ];\n        for( i = 0; i < iter; i++ ) {\n            if( nRshifts[ i ] > 0 ) {\n                sumBits_Q6 += nBits_ptr[ MAX_PULSES + 1 ];\n            } else {\n                sumBits_Q6 += nBits_ptr[ sum_pulses[ i ] ];\n            }\n        }\n        if( sumBits_Q6 < minSumBits_Q6 ) {\n            minSumBits_Q6 = sumBits_Q6;\n            RateLevelIndex = k;\n        }\n    }\n    SKP_Silk_range_encoder( psRC, RateLevelIndex, SKP_Silk_rate_levels_CDF[ sigtype ] );\n\n    /***************************************************/\n    /* Sum-Weighted-Pulses Encoding                    */\n    /***************************************************/\n    cdf_ptr = SKP_Silk_pulses_per_block_CDF[ RateLevelIndex ];\n    for( i = 0; i < iter; i++ ) {\n        if( nRshifts[ i ] == 0 ) {\n            SKP_Silk_range_encoder( psRC, sum_pulses[ i ], cdf_ptr );\n        } else {\n            SKP_Silk_range_encoder( psRC, MAX_PULSES + 1, cdf_ptr );\n            for( k = 0; k < nRshifts[ i ] - 1; k++ ) {\n                SKP_Silk_range_encoder( psRC, MAX_PULSES + 1, SKP_Silk_pulses_per_block_CDF[ N_RATE_LEVELS - 1 ] );\n            }\n            SKP_Silk_range_encoder( psRC, sum_pulses[ i ], SKP_Silk_pulses_per_block_CDF[ N_RATE_LEVELS - 1 ] );\n        }\n    }\n\n    /******************/\n    /* Shell Encoding */\n    /******************/\n    for( i = 0; i < iter; i++ ) {\n        if( sum_pulses[ i ] > 0 ) {\n            SKP_Silk_shell_encoder( psRC, &abs_pulses[ i * SHELL_CODEC_FRAME_LENGTH ] );\n        }\n    }\n\n    /****************/\n    /* LSB Encoding */\n    /****************/\n    for( i = 0; i < iter; i++ ) {\n        if( nRshifts[ i ] > 0 ) {\n            pulses_ptr = &q[ i * SHELL_CODEC_FRAME_LENGTH ];\n            nLS = nRshifts[ i ] - 1;\n            for( k = 0; k < SHELL_CODEC_FRAME_LENGTH; k++ ) {\n                abs_q = (SKP_int8)SKP_abs( pulses_ptr[ k ] );\n                for( j = nLS; j > 0; j-- ) {\n                    bit = SKP_RSHIFT( abs_q, j ) & 1;\n                    SKP_Silk_range_encoder( psRC, bit, SKP_Silk_lsb_CDF );\n                }\n                bit = abs_q & 1;\n                SKP_Silk_range_encoder( psRC, bit, SKP_Silk_lsb_CDF );\n            }\n        }\n    }\n\n    /****************/\n    /* Encode signs */\n    /****************/\n    SKP_Silk_encode_signs( psRC, q, frame_length, sigtype, QuantOffsetType, RateLevelIndex );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_find_LPC_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n#include \"SKP_Silk_tuning_parameters.h\"\n\n/* Finds LPC vector from correlations, and converts to NLSF */\nvoid SKP_Silk_find_LPC_FIX(\n    SKP_int             NLSF_Q15[],             /* O    NLSFs                                                                       */\n    SKP_int             *interpIndex,           /* O    NLSF interpolation index, only used for NLSF interpolation                  */\n    const SKP_int       prev_NLSFq_Q15[],       /* I    previous NLSFs, only used for NLSF interpolation                            */\n    const SKP_int       useInterpolatedNLSFs,   /* I    Flag                                                                        */\n    const SKP_int       LPC_order,              /* I    LPC order                                                                   */\n    const SKP_int16     x[],                    /* I    Input signal                                                                */\n    const SKP_int       subfr_length            /* I    Input signal subframe length including preceeding samples                   */\n)\n{\n    SKP_int     k;\n    SKP_int32   a_Q16[ MAX_LPC_ORDER ];\n    SKP_int     isInterpLower, shift;\n    SKP_int16   S[ MAX_LPC_ORDER ];\n    SKP_int32   res_nrg0, res_nrg1;\n    SKP_int     rshift0, rshift1; \n\n    /* Used only for LSF interpolation */\n    SKP_int32   a_tmp_Q16[ MAX_LPC_ORDER ], res_nrg_interp, res_nrg, res_tmp_nrg;\n    SKP_int     res_nrg_interp_Q, res_nrg_Q, res_tmp_nrg_Q;\n    SKP_int16   a_tmp_Q12[ MAX_LPC_ORDER ];\n    SKP_int     NLSF0_Q15[ MAX_LPC_ORDER ];\n    SKP_int16   LPC_res[ ( MAX_FRAME_LENGTH + NB_SUBFR * MAX_LPC_ORDER ) / 2 ];\n\n    /* Default: no interpolation */\n    *interpIndex = 4;\n\n    /* Burg AR analysis for the full frame */\n    SKP_Silk_burg_modified( &res_nrg, &res_nrg_Q, a_Q16, x, subfr_length, NB_SUBFR, SKP_FIX_CONST( FIND_LPC_COND_FAC, 32 ), LPC_order );\n\n    SKP_Silk_bwexpander_32( a_Q16, LPC_order, SKP_FIX_CONST( FIND_LPC_CHIRP, 16 ) );\n\n    if( useInterpolatedNLSFs == 1 ) {\n\n        /* Optimal solution for last 10 ms */\n        SKP_Silk_burg_modified( &res_tmp_nrg, &res_tmp_nrg_Q, a_tmp_Q16, x + ( NB_SUBFR >> 1 ) * subfr_length, \n            subfr_length, ( NB_SUBFR >> 1 ), SKP_FIX_CONST( FIND_LPC_COND_FAC, 32 ), LPC_order );\n\n        SKP_Silk_bwexpander_32( a_tmp_Q16, LPC_order, SKP_FIX_CONST( FIND_LPC_CHIRP, 16 ) );\n\n        /* subtract residual energy here, as that's easier than adding it to the    */\n        /* residual energy of the first 10 ms in each iteration of the search below */\n        shift = res_tmp_nrg_Q - res_nrg_Q;\n        if( shift >= 0 ) {\n            if( shift < 32 ) { \n                res_nrg = res_nrg - SKP_RSHIFT( res_tmp_nrg, shift );\n            }\n        } else {\n            SKP_assert( shift > -32 ); \n            res_nrg   = SKP_RSHIFT( res_nrg, -shift ) - res_tmp_nrg;\n            res_nrg_Q = res_tmp_nrg_Q; \n        }\n        \n        /* Convert to NLSFs */\n        SKP_Silk_A2NLSF( NLSF_Q15, a_tmp_Q16, LPC_order );\n\n        /* Search over interpolation indices to find the one with lowest residual energy */\n        for( k = 3; k >= 0; k-- ) {\n            /* Interpolate NLSFs for first half */\n            SKP_Silk_interpolate( NLSF0_Q15, prev_NLSFq_Q15, NLSF_Q15, k, LPC_order );\n\n            /* Convert to LPC for residual energy evaluation */\n            SKP_Silk_NLSF2A_stable( a_tmp_Q12, NLSF0_Q15, LPC_order );\n\n            /* Calculate residual energy with NLSF interpolation */\n            SKP_memset( S, 0, LPC_order * sizeof( SKP_int16 ) );\n            SKP_Silk_LPC_analysis_filter( x, a_tmp_Q12, S, LPC_res, 2 * subfr_length, LPC_order );\n\n            SKP_Silk_sum_sqr_shift( &res_nrg0, &rshift0, LPC_res + LPC_order,                subfr_length - LPC_order );\n            SKP_Silk_sum_sqr_shift( &res_nrg1, &rshift1, LPC_res + LPC_order + subfr_length, subfr_length - LPC_order );\n\n            /* Add subframe energies from first half frame */\n            shift = rshift0 - rshift1;\n            if( shift >= 0 ) {\n                res_nrg1         = SKP_RSHIFT( res_nrg1, shift );\n                res_nrg_interp_Q = -rshift0;\n            } else {\n                res_nrg0         = SKP_RSHIFT( res_nrg0, -shift );\n                res_nrg_interp_Q = -rshift1;\n            }\n            res_nrg_interp = SKP_ADD32( res_nrg0, res_nrg1 );\n\n            /* Compare with first half energy without NLSF interpolation, or best interpolated value so far */\n            shift = res_nrg_interp_Q - res_nrg_Q;\n            if( shift >= 0 ) {\n                if( SKP_RSHIFT( res_nrg_interp, shift ) < res_nrg ) {\n                    isInterpLower = SKP_TRUE;\n                } else {\n                    isInterpLower = SKP_FALSE;\n                }\n            } else {\n                if( -shift < 32 ) { \n                    if( res_nrg_interp < SKP_RSHIFT( res_nrg, -shift ) ) {\n                        isInterpLower = SKP_TRUE;\n                    } else {\n                        isInterpLower = SKP_FALSE;\n                    }\n                } else {\n                    isInterpLower = SKP_FALSE;\n                }\n            }\n\n            /* Determine whether current interpolated NLSFs are best so far */\n            if( isInterpLower == SKP_TRUE ) {\n                /* Interpolation has lower residual energy */\n                res_nrg   = res_nrg_interp;\n                res_nrg_Q = res_nrg_interp_Q;\n                *interpIndex = k;\n            }\n        }\n    }\n\n    if( *interpIndex == 4 ) {\n        /* NLSF interpolation is currently inactive, calculate NLSFs from full frame AR coefficients */\n        SKP_Silk_A2NLSF( NLSF_Q15, a_Q16, LPC_order );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_find_LTP_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n#include \"SKP_Silk_tuning_parameters.h\"\n\n/* Head room for correlations                           */\n#define LTP_CORRS_HEAD_ROOM                             2\n\nvoid SKP_Silk_fit_LTP(\n    SKP_int32 LTP_coefs_Q16[ LTP_ORDER ],\n    SKP_int16 LTP_coefs_Q14[ LTP_ORDER ]\n);\n\nvoid SKP_Silk_find_LTP_FIX(\n    SKP_int16           b_Q14[ NB_SUBFR * LTP_ORDER ],              /* O    LTP coefs                                                   */\n    SKP_int32           WLTP[ NB_SUBFR * LTP_ORDER * LTP_ORDER ],   /* O    Weight for LTP quantization                                 */\n    SKP_int             *LTPredCodGain_Q7,                          /* O    LTP coding gain                                             */\n    const SKP_int16     r_first[],                                  /* I    residual signal after LPC signal + state for first 10 ms    */\n    const SKP_int16     r_last[],                                   /* I    residual signal after LPC signal + state for last 10 ms     */\n    const SKP_int       lag[ NB_SUBFR ],                            /* I    LTP lags                                                    */\n    const SKP_int32     Wght_Q15[ NB_SUBFR ],                       /* I    weights                                                     */\n    const SKP_int       subfr_length,                               /* I    subframe length                                             */\n    const SKP_int       mem_offset,                                 /* I    number of samples in LTP memory                             */\n    SKP_int             corr_rshifts[ NB_SUBFR ]                    /* O    right shifts applied to correlations                        */\n)\n{\n    SKP_int   i, k, lshift;\n    const SKP_int16 *r_ptr, *lag_ptr;\n    SKP_int16 *b_Q14_ptr;\n\n    SKP_int32 regu;\n    SKP_int32 *WLTP_ptr;\n    SKP_int32 b_Q16[ LTP_ORDER ], delta_b_Q14[ LTP_ORDER ], d_Q14[ NB_SUBFR ], nrg[ NB_SUBFR ], g_Q26;\n    SKP_int32 w[ NB_SUBFR ], WLTP_max, max_abs_d_Q14, max_w_bits;\n\n    SKP_int32 temp32, denom32;\n    SKP_int   extra_shifts;\n    SKP_int   rr_shifts, maxRshifts, maxRshifts_wxtra, LZs;\n    SKP_int32 LPC_res_nrg, LPC_LTP_res_nrg, div_Q16;\n    SKP_int32 Rr[ LTP_ORDER ], rr[ NB_SUBFR ];\n    SKP_int32 wd, m_Q12;\n    \n    b_Q14_ptr = b_Q14;\n    WLTP_ptr  = WLTP;\n    r_ptr     = &r_first[ mem_offset ];\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        if( k == ( NB_SUBFR >> 1 ) ) { /* shift residual for last 10 ms */\n            r_ptr = &r_last[ mem_offset ];\n        }\n        lag_ptr = r_ptr - ( lag[ k ] + LTP_ORDER / 2 );\n\n        SKP_Silk_sum_sqr_shift( &rr[ k ], &rr_shifts, r_ptr, subfr_length ); /* rr[ k ] in Q( -rr_shifts ) */\n\n        /* Assure headroom */\n        LZs = SKP_Silk_CLZ32( rr[k] );\n        if( LZs < LTP_CORRS_HEAD_ROOM ) {\n            rr[ k ] = SKP_RSHIFT_ROUND( rr[ k ], LTP_CORRS_HEAD_ROOM - LZs );\n            rr_shifts += ( LTP_CORRS_HEAD_ROOM - LZs );\n        }\n        corr_rshifts[ k ] = rr_shifts;\n        SKP_Silk_corrMatrix_FIX( lag_ptr, subfr_length, LTP_ORDER, LTP_CORRS_HEAD_ROOM, WLTP_ptr, &corr_rshifts[ k ] );  /* WLTP_fix_ptr in Q( -corr_rshifts[ k ] ) */\n\n        /* The correlation vector always has lower max abs value than rr and/or RR so head room is assured */\n        SKP_Silk_corrVector_FIX( lag_ptr, r_ptr, subfr_length, LTP_ORDER, Rr, corr_rshifts[ k ] );  /* Rr_fix_ptr   in Q( -corr_rshifts[ k ] ) */\n        if( corr_rshifts[ k ] > rr_shifts ) {\n            rr[ k ] = SKP_RSHIFT( rr[ k ], corr_rshifts[ k ] - rr_shifts ); /* rr[ k ] in Q( -corr_rshifts[ k ] ) */\n        }\n        SKP_assert( rr[ k ] >= 0 );\n\n        regu = 1;\n        regu = SKP_SMLAWB( regu, rr[ k ], SKP_FIX_CONST( LTP_DAMPING/3, 16 ) );\n        regu = SKP_SMLAWB( regu, matrix_ptr( WLTP_ptr, 0, 0, LTP_ORDER ), SKP_FIX_CONST( LTP_DAMPING/3, 16 ) );\n        regu = SKP_SMLAWB( regu, matrix_ptr( WLTP_ptr, LTP_ORDER-1, LTP_ORDER-1, LTP_ORDER ), SKP_FIX_CONST( LTP_DAMPING/3, 16 ) );\n        SKP_Silk_regularize_correlations_FIX( WLTP_ptr, &rr[k], regu, LTP_ORDER );\n\n        SKP_Silk_solve_LDL_FIX( WLTP_ptr, LTP_ORDER, Rr, b_Q16 ); /* WLTP_fix_ptr and Rr_fix_ptr both in Q(-corr_rshifts[k]) */\n\n        /* Limit and store in Q14 */\n        SKP_Silk_fit_LTP( b_Q16, b_Q14_ptr );\n\n        /* Calculate residual energy */\n        nrg[ k ] = SKP_Silk_residual_energy16_covar_FIX( b_Q14_ptr, WLTP_ptr, Rr, rr[ k ], LTP_ORDER, 14 ); /* nrg_fix in Q( -corr_rshifts[ k ] ) */\n\n        /* temp = Wght[ k ] / ( nrg[ k ] * Wght[ k ] + 0.01f * subfr_length ); */\n        extra_shifts = SKP_min_int( corr_rshifts[ k ], LTP_CORRS_HEAD_ROOM );\n        denom32 = SKP_LSHIFT_SAT32( SKP_SMULWB( nrg[ k ], Wght_Q15[ k ] ), 1 + extra_shifts ) + /* Q( -corr_rshifts[ k ] + extra_shifts ) */\n            SKP_RSHIFT( SKP_SMULWB( subfr_length, 655 ), corr_rshifts[ k ] - extra_shifts );    /* Q( -corr_rshifts[ k ] + extra_shifts ) */\n        denom32 = SKP_max( denom32, 1 );\n        SKP_assert( ((SKP_int64)Wght_Q15[ k ] << 16 ) < SKP_int32_MAX );                        /* Wght always < 0.5 in Q0 */\n        temp32 = SKP_DIV32( SKP_LSHIFT( ( SKP_int32 )Wght_Q15[ k ], 16 ), denom32 );            /* Q( 15 + 16 + corr_rshifts[k] - extra_shifts ) */\n        temp32 = SKP_RSHIFT( temp32, 31 + corr_rshifts[ k ] - extra_shifts - 26 );              /* Q26 */\n        \n        /* Limit temp such that the below scaling never wraps around */\n        WLTP_max = 0;\n        for( i = 0; i < LTP_ORDER * LTP_ORDER; i++ ) {\n            WLTP_max = SKP_max( WLTP_ptr[ i ], WLTP_max );\n        }\n        lshift = SKP_Silk_CLZ32( WLTP_max ) - 1 - 3; /* keep 3 bits free for vq_nearest_neighbor_fix */\n        SKP_assert( 26 - 18 + lshift >= 0 );\n        if( 26 - 18 + lshift < 31 ) {\n            temp32 = SKP_min_32( temp32, SKP_LSHIFT( ( SKP_int32 )1, 26 - 18 + lshift ) );\n        }\n\n        SKP_Silk_scale_vector32_Q26_lshift_18( WLTP_ptr, temp32, LTP_ORDER * LTP_ORDER ); /* WLTP_ptr in Q( 18 - corr_rshifts[ k ] ) */\n        \n        w[ k ] = matrix_ptr( WLTP_ptr, ( LTP_ORDER >> 1 ), ( LTP_ORDER >> 1 ), LTP_ORDER ); /* w in Q( 18 - corr_rshifts[ k ] ) */\n        SKP_assert( w[k] >= 0 );\n\n        r_ptr     += subfr_length;\n        b_Q14_ptr += LTP_ORDER;\n        WLTP_ptr  += LTP_ORDER * LTP_ORDER;\n    }\n\n    maxRshifts = 0;\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        maxRshifts = SKP_max_int( corr_rshifts[ k ], maxRshifts );\n    }\n\n    /* Compute LTP coding gain */\n    if( LTPredCodGain_Q7 != NULL ) {\n        LPC_LTP_res_nrg = 0;\n        LPC_res_nrg     = 0;\n        SKP_assert( LTP_CORRS_HEAD_ROOM >= 2 ); /* Check that no overflow will happen when adding */\n        for( k = 0; k < NB_SUBFR; k++ ) {\n            LPC_res_nrg     = SKP_ADD32( LPC_res_nrg,     SKP_RSHIFT( SKP_ADD32( SKP_SMULWB(  rr[ k ], Wght_Q15[ k ] ), 1 ), 1 + ( maxRshifts - corr_rshifts[ k ] ) ) ); /*  Q( -maxRshifts ) */\n            LPC_LTP_res_nrg = SKP_ADD32( LPC_LTP_res_nrg, SKP_RSHIFT( SKP_ADD32( SKP_SMULWB( nrg[ k ], Wght_Q15[ k ] ), 1 ), 1 + ( maxRshifts - corr_rshifts[ k ] ) ) ); /*  Q( -maxRshifts ) */\n        }\n        LPC_LTP_res_nrg = SKP_max( LPC_LTP_res_nrg, 1 ); /* avoid division by zero */\n\n        div_Q16 = SKP_DIV32_varQ( LPC_res_nrg, LPC_LTP_res_nrg, 16 );\n        *LTPredCodGain_Q7 = ( SKP_int )SKP_SMULBB( 3, SKP_Silk_lin2log( div_Q16 ) - ( 16 << 7 ) );\n\n        SKP_assert( *LTPredCodGain_Q7 == ( SKP_int )SKP_SAT16( SKP_MUL( 3, SKP_Silk_lin2log( div_Q16 ) - ( 16 << 7 ) ) ) );\n    }\n\n    /* smoothing */\n    /* d = sum( B, 1 ); */\n    b_Q14_ptr = b_Q14;\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        d_Q14[ k ] = 0;\n        for( i = 0; i < LTP_ORDER; i++ ) {\n            d_Q14[ k ] += b_Q14_ptr[ i ];\n        }\n        b_Q14_ptr += LTP_ORDER;\n    }\n\n    /* m = ( w * d' ) / ( sum( w ) + 1e-3 ); */\n        \n    /* Find maximum absolute value of d_Q14 and the bits used by w in Q0 */\n    max_abs_d_Q14 = 0;\n    max_w_bits    = 0;\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        max_abs_d_Q14 = SKP_max_32( max_abs_d_Q14, SKP_abs( d_Q14[ k ] ) );\n        /* w[ k ] is in Q( 18 - corr_rshifts[ k ] ) */\n        /* Find bits needed in Q( 18 - maxRshifts ) */\n        max_w_bits = SKP_max_32( max_w_bits, 32 - SKP_Silk_CLZ32( w[ k ] ) + corr_rshifts[ k ] - maxRshifts ); \n    }\n\n    /* max_abs_d_Q14 = (5 << 15); worst case, i.e. LTP_ORDER * -SKP_int16_MIN */\n    SKP_assert( max_abs_d_Q14 <= ( 5 << 15 ) );\n\n    /* How many bits is needed for w*d' in Q( 18 - maxRshifts ) in the worst case, of all d_Q14's being equal to max_abs_d_Q14 */\n    extra_shifts = max_w_bits + 32 - SKP_Silk_CLZ32( max_abs_d_Q14 ) - 14;\n    \n    /* Subtract what we got available; bits in output var plus maxRshifts */\n    extra_shifts -= ( 32 - 1 - 2 + maxRshifts ); /* Keep sign bit free as well as 2 bits for accumulation */\n    extra_shifts = SKP_max_int( extra_shifts, 0 );\n\n    maxRshifts_wxtra = maxRshifts + extra_shifts;\n    \n    temp32 = SKP_RSHIFT( 262, maxRshifts + extra_shifts ) + 1; /* 1e-3f in Q( 18 - (maxRshifts + extra_shifts) ) */\n    wd = 0;\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        /* w has at least 2 bits of headroom so no overflow should happen */\n        temp32 = SKP_ADD32( temp32,                     SKP_RSHIFT( w[ k ], maxRshifts_wxtra - corr_rshifts[ k ] ) );                    /* Q( 18 - maxRshifts_wxtra ) */\n        wd     = SKP_ADD32( wd, SKP_LSHIFT( SKP_SMULWW( SKP_RSHIFT( w[ k ], maxRshifts_wxtra - corr_rshifts[ k ] ), d_Q14[ k ] ), 2 ) ); /* Q( 18 - maxRshifts_wxtra ) */\n    }\n    m_Q12 = SKP_DIV32_varQ( wd, temp32, 12 );\n\n    b_Q14_ptr = b_Q14;\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        /* w_fix[ k ] from Q( 18 - corr_rshifts[ k ] ) to Q( 16 ) */\n        if( 2 - corr_rshifts[k] > 0 ) {\n            temp32 = SKP_RSHIFT( w[ k ], 2 - corr_rshifts[ k ] );\n        } else {\n            temp32 = SKP_LSHIFT_SAT32( w[ k ], corr_rshifts[ k ] - 2 );\n        }\n\n        g_Q26 = SKP_MUL( \n            SKP_DIV32( \n                SKP_FIX_CONST( LTP_SMOOTHING, 26 ), \n                SKP_RSHIFT( SKP_FIX_CONST( LTP_SMOOTHING, 26 ), 10 ) + temp32 ),                                       /* Q10 */ \n            SKP_LSHIFT_SAT32( SKP_SUB_SAT32( ( SKP_int32 )m_Q12, SKP_RSHIFT( d_Q14[ k ], 2 ) ), 4 ) );  /* Q16 */\n\n        temp32 = 0;\n        for( i = 0; i < LTP_ORDER; i++ ) {\n            delta_b_Q14[ i ] = SKP_max_16( b_Q14_ptr[ i ], 1638 );  /* 1638_Q14 = 0.1_Q0 */\n            temp32 += delta_b_Q14[ i ];                          /* Q14 */\n        }\n        temp32 = SKP_DIV32( g_Q26, temp32 ); /* Q14->Q12 */\n        for( i = 0; i < LTP_ORDER; i++ ) {\n            b_Q14_ptr[ i ] = SKP_LIMIT_32( ( SKP_int32 )b_Q14_ptr[ i ] + SKP_SMULWB( SKP_LSHIFT_SAT32( temp32, 4 ), delta_b_Q14[ i ] ), -16000, 28000 );\n        }\n        b_Q14_ptr += LTP_ORDER;\n    }\n}\n\nvoid SKP_Silk_fit_LTP(\n    SKP_int32 LTP_coefs_Q16[ LTP_ORDER ],\n    SKP_int16 LTP_coefs_Q14[ LTP_ORDER ]\n)\n{\n    SKP_int i;\n\n    for( i = 0; i < LTP_ORDER; i++ ) {\n        LTP_coefs_Q14[ i ] = ( SKP_int16 )SKP_SAT16( SKP_RSHIFT_ROUND( LTP_coefs_Q16[ i ], 2 ) );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_find_pitch_lags_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n#include \"SKP_Silk_tuning_parameters.h\"\n\n/* Find pitch lags */\nvoid SKP_Silk_find_pitch_lags_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,         /* I/O  encoder state                               */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl,     /* I/O  encoder control                             */\n    SKP_int16                       res[],          /* O    residual                                    */\n    const SKP_int16                 x[]             /* I    Speech signal                               */\n)\n{\n    SKP_Silk_predict_state_FIX *psPredSt = &psEnc->sPred;\n    SKP_int   buf_len, i, scale;\n    SKP_int32 thrhld_Q15, res_nrg;\n    const SKP_int16 *x_buf, *x_buf_ptr;\n    SKP_int16 Wsig[      FIND_PITCH_LPC_WIN_MAX ], *Wsig_ptr;\n    SKP_int32 auto_corr[ MAX_FIND_PITCH_LPC_ORDER + 1 ];\n    SKP_int16 rc_Q15[    MAX_FIND_PITCH_LPC_ORDER ];\n    SKP_int32 A_Q24[     MAX_FIND_PITCH_LPC_ORDER ];\n    SKP_int32 FiltState[ MAX_FIND_PITCH_LPC_ORDER ];\n    SKP_int16 A_Q12[     MAX_FIND_PITCH_LPC_ORDER ];\n\n    /******************************************/\n    /* Setup buffer lengths etc based on Fs   */\n    /******************************************/\n    buf_len = SKP_ADD_LSHIFT( psEnc->sCmn.la_pitch, psEnc->sCmn.frame_length, 1 );\n\n    /* Safty check */\n    SKP_assert( buf_len >= psPredSt->pitch_LPC_win_length );\n\n    x_buf = x - psEnc->sCmn.frame_length;\n\n    /*************************************/\n    /* Estimate LPC AR coefficients      */\n    /*************************************/\n    \n    /* Calculate windowed signal */\n    \n    /* First LA_LTP samples */\n    x_buf_ptr = x_buf + buf_len - psPredSt->pitch_LPC_win_length;\n    Wsig_ptr  = Wsig;\n    SKP_Silk_apply_sine_window( Wsig_ptr, x_buf_ptr, 1, psEnc->sCmn.la_pitch );\n\n    /* Middle un - windowed samples */\n    Wsig_ptr  += psEnc->sCmn.la_pitch;\n    x_buf_ptr += psEnc->sCmn.la_pitch;\n    SKP_memcpy( Wsig_ptr, x_buf_ptr, ( psPredSt->pitch_LPC_win_length - SKP_LSHIFT( psEnc->sCmn.la_pitch, 1 ) ) * sizeof( SKP_int16 ) );\n\n    /* Last LA_LTP samples */\n    Wsig_ptr  += psPredSt->pitch_LPC_win_length - SKP_LSHIFT( psEnc->sCmn.la_pitch, 1 );\n    x_buf_ptr += psPredSt->pitch_LPC_win_length - SKP_LSHIFT( psEnc->sCmn.la_pitch, 1 );\n    SKP_Silk_apply_sine_window( Wsig_ptr, x_buf_ptr, 2, psEnc->sCmn.la_pitch );\n\n    /* Calculate autocorrelation sequence */\n    SKP_Silk_autocorr( auto_corr, &scale, Wsig, psPredSt->pitch_LPC_win_length, psEnc->sCmn.pitchEstimationLPCOrder + 1 ); \n        \n    /* Add white noise, as fraction of energy */\n    auto_corr[ 0 ] = SKP_SMLAWB( auto_corr[ 0 ], auto_corr[ 0 ], SKP_FIX_CONST( FIND_PITCH_WHITE_NOISE_FRACTION, 16 ) );\n\n    /* Calculate the reflection coefficients using schur */\n    res_nrg = SKP_Silk_schur( rc_Q15, auto_corr, psEnc->sCmn.pitchEstimationLPCOrder );\n\n    /* Prediction gain */\n    psEncCtrl->predGain_Q16 = SKP_DIV32_varQ( auto_corr[ 0 ], SKP_max_int( res_nrg, 1 ), 16 );\n\n    /* Convert reflection coefficients to prediction coefficients */\n    SKP_Silk_k2a( A_Q24, rc_Q15, psEnc->sCmn.pitchEstimationLPCOrder );\n    \n    /* Convert From 32 bit Q24 to 16 bit Q12 coefs */\n    for( i = 0; i < psEnc->sCmn.pitchEstimationLPCOrder; i++ ) {\n        A_Q12[ i ] = ( SKP_int16 )SKP_SAT16( SKP_RSHIFT( A_Q24[ i ], 12 ) );\n    }\n\n    /* Do BWE */\n    SKP_Silk_bwexpander( A_Q12, psEnc->sCmn.pitchEstimationLPCOrder, SKP_FIX_CONST( FIND_PITCH_BANDWITH_EXPANSION, 16 ) );\n    \n    /*****************************************/\n    /* LPC analysis filtering                */\n    /*****************************************/\n    SKP_memset( FiltState, 0, psEnc->sCmn.pitchEstimationLPCOrder * sizeof( SKP_int32 ) ); /* Not really necessary, but Valgrind will complain otherwise */\n    SKP_Silk_MA_Prediction( x_buf, A_Q12, FiltState, res, buf_len, psEnc->sCmn.pitchEstimationLPCOrder );\n    SKP_memset( res, 0, psEnc->sCmn.pitchEstimationLPCOrder * sizeof( SKP_int16 ) );\n\n    /* Threshold for pitch estimator */\n    thrhld_Q15 = SKP_FIX_CONST( 0.45, 15 );\n    thrhld_Q15 = SKP_SMLABB( thrhld_Q15, SKP_FIX_CONST( -0.004, 15 ), psEnc->sCmn.pitchEstimationLPCOrder );\n    thrhld_Q15 = SKP_SMLABB( thrhld_Q15, SKP_FIX_CONST( -0.1,   7  ), psEnc->speech_activity_Q8 );\n    thrhld_Q15 = SKP_SMLABB( thrhld_Q15, SKP_FIX_CONST(  0.15,  15 ), psEnc->sCmn.prev_sigtype );\n    thrhld_Q15 = SKP_SMLAWB( thrhld_Q15, SKP_FIX_CONST( -0.1,   16 ), psEncCtrl->input_tilt_Q15 );\n    thrhld_Q15 = SKP_SAT16(  thrhld_Q15 );\n\n    /*****************************************/\n    /* Call pitch estimator                  */\n    /*****************************************/\n    psEncCtrl->sCmn.sigtype = SKP_Silk_pitch_analysis_core( res, psEncCtrl->sCmn.pitchL, &psEncCtrl->sCmn.lagIndex, \n        &psEncCtrl->sCmn.contourIndex, &psEnc->LTPCorr_Q15, psEnc->sCmn.prevLag, psEnc->sCmn.pitchEstimationThreshold_Q16, \n        ( SKP_int16 )thrhld_Q15, psEnc->sCmn.fs_kHz, psEnc->sCmn.pitchEstimationComplexity, SKP_FALSE );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_find_pred_coefs_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\n\nvoid SKP_Silk_find_pred_coefs_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,         /* I/O  encoder state                               */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl,     /* I/O  encoder control                             */\n    const SKP_int16                 res_pitch[]     /* I    Residual from pitch analysis                */\n)\n{\n    SKP_int         i;\n    SKP_int32       WLTP[ NB_SUBFR * LTP_ORDER * LTP_ORDER ];\n    SKP_int32       invGains_Q16[ NB_SUBFR ], local_gains[ NB_SUBFR ], Wght_Q15[ NB_SUBFR ];\n    SKP_int         NLSF_Q15[ MAX_LPC_ORDER ];\n    const SKP_int16 *x_ptr;\n    SKP_int16       *x_pre_ptr, LPC_in_pre[ NB_SUBFR * MAX_LPC_ORDER + MAX_FRAME_LENGTH ];\n    SKP_int32       tmp, min_gain_Q16;\n    SKP_int         LTP_corrs_rshift[ NB_SUBFR ];\n\n\n    /* weighting for weighted least squares */\n    min_gain_Q16 = SKP_int32_MAX >> 6;\n    for( i = 0; i < NB_SUBFR; i++ ) {\n        min_gain_Q16 = SKP_min( min_gain_Q16, psEncCtrl->Gains_Q16[ i ] );\n    }\n    for( i = 0; i < NB_SUBFR; i++ ) {\n        /* Divide to Q16 */\n        SKP_assert( psEncCtrl->Gains_Q16[ i ] > 0 );\n        /* Invert and normalize gains, and ensure that maximum invGains_Q16 is within range of a 16 bit int */\n        invGains_Q16[ i ] = SKP_DIV32_varQ( min_gain_Q16, psEncCtrl->Gains_Q16[ i ], 16 - 2 );\n\n        /* Ensure Wght_Q15 a minimum value 1 */\n        invGains_Q16[ i ] = SKP_max( invGains_Q16[ i ], 363 ); \n        \n        /* Square the inverted gains */\n        SKP_assert( invGains_Q16[ i ] == SKP_SAT16( invGains_Q16[ i ] ) );\n        tmp = SKP_SMULWB( invGains_Q16[ i ], invGains_Q16[ i ] );\n        Wght_Q15[ i ] = SKP_RSHIFT( tmp, 1 );\n\n        /* Invert the inverted and normalized gains */\n        local_gains[ i ] = SKP_DIV32( ( 1 << 16 ), invGains_Q16[ i ] );\n    }\n\n    if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) {\n        /**********/\n        /* VOICED */\n        /**********/\n        SKP_assert( psEnc->sCmn.frame_length - psEnc->sCmn.predictLPCOrder >= psEncCtrl->sCmn.pitchL[ 0 ] + LTP_ORDER / 2 );\n\n        /* LTP analysis */\n        SKP_Silk_find_LTP_FIX( psEncCtrl->LTPCoef_Q14, WLTP, &psEncCtrl->LTPredCodGain_Q7, res_pitch, \n            res_pitch + SKP_RSHIFT( psEnc->sCmn.frame_length, 1 ), psEncCtrl->sCmn.pitchL, Wght_Q15, \n            psEnc->sCmn.subfr_length, psEnc->sCmn.frame_length, LTP_corrs_rshift );\n\n\n        /* Quantize LTP gain parameters */\n        SKP_Silk_quant_LTP_gains_FIX( psEncCtrl->LTPCoef_Q14, psEncCtrl->sCmn.LTPIndex, &psEncCtrl->sCmn.PERIndex, \n            WLTP, psEnc->mu_LTP_Q8, psEnc->sCmn.LTPQuantLowComplexity );\n\n        /* Control LTP scaling */\n        SKP_Silk_LTP_scale_ctrl_FIX( psEnc, psEncCtrl );\n\n        /* Create LTP residual */\n        SKP_Silk_LTP_analysis_filter_FIX( LPC_in_pre, psEnc->x_buf + psEnc->sCmn.frame_length - psEnc->sCmn.predictLPCOrder, \n            psEncCtrl->LTPCoef_Q14, psEncCtrl->sCmn.pitchL, invGains_Q16, psEnc->sCmn.subfr_length, psEnc->sCmn.predictLPCOrder );\n\n    } else {\n        /************/\n        /* UNVOICED */\n        /************/\n        /* Create signal with prepended subframes, scaled by inverse gains */\n        x_ptr     = psEnc->x_buf + psEnc->sCmn.frame_length - psEnc->sCmn.predictLPCOrder;\n        x_pre_ptr = LPC_in_pre;\n        for( i = 0; i < NB_SUBFR; i++ ) {\n            SKP_Silk_scale_copy_vector16( x_pre_ptr, x_ptr, invGains_Q16[ i ], \n                psEnc->sCmn.subfr_length + psEnc->sCmn.predictLPCOrder );\n            x_pre_ptr += psEnc->sCmn.subfr_length + psEnc->sCmn.predictLPCOrder;\n            x_ptr     += psEnc->sCmn.subfr_length;\n        }\n\n        SKP_memset( psEncCtrl->LTPCoef_Q14, 0, NB_SUBFR * LTP_ORDER * sizeof( SKP_int16 ) );\n        psEncCtrl->LTPredCodGain_Q7 = 0;\n    }\n\n    /* LPC_in_pre contains the LTP-filtered input for voiced, and the unfiltered input for unvoiced */\n    TIC(FIND_LPC)\n    SKP_Silk_find_LPC_FIX( NLSF_Q15, &psEncCtrl->sCmn.NLSFInterpCoef_Q2, psEnc->sPred.prev_NLSFq_Q15, \n        psEnc->sCmn.useInterpolatedNLSFs * ( 1 - psEnc->sCmn.first_frame_after_reset ), psEnc->sCmn.predictLPCOrder, \n        LPC_in_pre, psEnc->sCmn.subfr_length + psEnc->sCmn.predictLPCOrder );\n    TOC(FIND_LPC)\n\n\n    /* Quantize LSFs */\n    TIC(PROCESS_LSFS)\n        SKP_Silk_process_NLSFs_FIX( psEnc, psEncCtrl, NLSF_Q15 );\n    TOC(PROCESS_LSFS)\n\n    /* Calculate residual energy using quantized LPC coefficients */\n    SKP_Silk_residual_energy_FIX( psEncCtrl->ResNrg, psEncCtrl->ResNrgQ, LPC_in_pre, psEncCtrl->PredCoef_Q12, local_gains,\n        psEnc->sCmn.subfr_length, psEnc->sCmn.predictLPCOrder );\n\n    /* Copy to prediction struct for use in next frame for fluctuation reduction */\n    SKP_memcpy( psEnc->sPred.prev_NLSFq_Q15, NLSF_Q15, psEnc->sCmn.predictLPCOrder * sizeof( SKP_int ) );\n\n}\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_gain_quant.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n#define OFFSET          ( ( MIN_QGAIN_DB * 128 ) / 6 + 16 * 128 )\n#define SCALE_Q16       ( ( 65536 * ( N_LEVELS_QGAIN - 1 ) ) / ( ( ( MAX_QGAIN_DB - MIN_QGAIN_DB ) * 128 ) / 6 ) )\n#define INV_SCALE_Q16   ( ( 65536 * ( ( ( MAX_QGAIN_DB - MIN_QGAIN_DB ) * 128 ) / 6 ) ) / ( N_LEVELS_QGAIN - 1 ) )\n\n/* Gain scalar quantization with hysteresis, uniform on log scale */\nvoid SKP_Silk_gains_quant(\n    SKP_int                         ind[ NB_SUBFR ],        /* O    gain indices                            */\n    SKP_int32                       gain_Q16[ NB_SUBFR ],   /* I/O  gains (quantized out)                   */\n    SKP_int                         *prev_ind,              /* I/O  last index in previous frame            */\n    const SKP_int                   conditional             /* I    first gain is delta coded if 1          */\n)\n{\n    SKP_int k;\n\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        /* Add half of previous quantization error, convert to log scale, scale, floor() */\n        ind[ k ] = SKP_SMULWB( SCALE_Q16, SKP_Silk_lin2log( gain_Q16[ k ] ) - OFFSET );\n\n        /* Round towards previous quantized gain (hysteresis) */\n        if( ind[ k ] < *prev_ind ) {\n            ind[ k ]++;\n        }\n\n        /* Compute delta indices and limit */\n        if( k == 0 && conditional == 0 ) {\n            /* Full index */\n            ind[ k ] = SKP_LIMIT_int( ind[ k ], 0, N_LEVELS_QGAIN - 1 );\n            ind[ k ] = SKP_max_int( ind[ k ], *prev_ind + MIN_DELTA_GAIN_QUANT );\n            *prev_ind = ind[ k ];\n        } else {\n            /* Delta index */\n            ind[ k ] = SKP_LIMIT_int( ind[ k ] - *prev_ind, MIN_DELTA_GAIN_QUANT, MAX_DELTA_GAIN_QUANT );\n            /* Accumulate deltas */\n            *prev_ind += ind[ k ];\n            /* Shift to make non-negative */\n            ind[ k ] -= MIN_DELTA_GAIN_QUANT;\n        }\n\n        /* Convert to linear scale and scale */\n        gain_Q16[ k ] = SKP_Silk_log2lin( SKP_min_32( SKP_SMULWB( INV_SCALE_Q16, *prev_ind ) + OFFSET, 3967 ) ); /* 3968 = 31 in Q7 */\n    }\n}\n\n/* Gains scalar dequantization, uniform on log scale */\nvoid SKP_Silk_gains_dequant(\n    SKP_int32                       gain_Q16[ NB_SUBFR ],   /* O    quantized gains                         */\n    const SKP_int                   ind[ NB_SUBFR ],        /* I    gain indices                            */\n    SKP_int                         *prev_ind,              /* I/O  last index in previous frame            */\n    const SKP_int                   conditional             /* I    first gain is delta coded if 1          */\n)\n{\n    SKP_int   k;\n\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        if( k == 0 && conditional == 0 ) {\n            *prev_ind = ind[ k ];\n        } else {\n            /* Delta index */\n            *prev_ind += ind[ k ] + MIN_DELTA_GAIN_QUANT;\n        }\n\n        /* Convert to linear scale and scale */\n        gain_Q16[ k ] = SKP_Silk_log2lin( SKP_min_32( SKP_SMULWB( INV_SCALE_Q16, *prev_ind ) + OFFSET, 3967 ) ); /* 3968 = 31 in Q7 */\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_init_encoder_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\n/*********************************/\n/* Initialize Silk Encoder state */\n/*********************************/\nSKP_int SKP_Silk_init_encoder_FIX(\n    SKP_Silk_encoder_state_FIX  *psEnc                  /* I/O  Pointer to Silk FIX encoder state       */\n) {\n    SKP_int ret = 0;\n    /* Clear the entire encoder state */\n    SKP_memset( psEnc, 0, sizeof( SKP_Silk_encoder_state_FIX ) );\n\n#if HIGH_PASS_INPUT\n    psEnc->variable_HP_smth1_Q15 = 200844; /* = SKP_Silk_log2(70)_Q0; */\n    psEnc->variable_HP_smth2_Q15 = 200844; /* = SKP_Silk_log2(70)_Q0; */\n#endif\n\n    /* Used to deactivate e.g. LSF interpolation and fluctuation reduction */\n    psEnc->sCmn.first_frame_after_reset = 1;\n\n    /* Initialize Silk VAD */\n    ret += SKP_Silk_VAD_Init( &psEnc->sCmn.sVAD );\n\n    /* Initialize NSQ */\n    psEnc->sCmn.sNSQ.prev_inv_gain_Q16      = 65536;\n    psEnc->sCmn.sNSQ_LBRR.prev_inv_gain_Q16 = 65536;\n\n    return( ret );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_inner_prod_aligned.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                                *\n * SKP_Silk_inner_prod_aligned.c                                                *\n *                                                                                *\n *                                                                          \t   *\n * Copyright 2008-2010 (c), Skype Limited                                              *\n * Date: 080601                                                                   *\n *                                                                                */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* sum= for(i=0;i<len;i++)inVec1[i]*inVec2[i];      ---        inner product    */\n/* Note for ARM asm:                                                            */\n/*        * inVec1 and inVec2 should be at least 2 byte aligned.    (Or defined as short/int16) */\n/*        * len should be positive 16bit integer.                               */\n/*        * only when len>6, memory access can be reduced by half.              */\n\n#if (EMBEDDED_ARM<5) \nSKP_int32 SKP_Silk_inner_prod_aligned(\n    const SKP_int16* const inVec1,  /*    I input vector 1    */\n    const SKP_int16* const inVec2,  /*    I input vector 2    */\n    const SKP_int             len   /*    I vector lengths    */\n)\n{\n    SKP_int   i; \n    SKP_int32 sum = 0;\n    for( i = 0; i < len; i++ ) {\n        sum = SKP_SMLABB( sum, inVec1[ i ], inVec2[ i ] );\n    }\n    return sum;\n}\n#endif\n\n#if (EMBEDDED_ARM<5) \nSKP_int64 SKP_Silk_inner_prod16_aligned_64(\n    const SKP_int16 *inVec1,        /*    I input vector 1    */ \n    const SKP_int16 *inVec2,        /*    I input vector 2    */\n    const SKP_int   len             /*    I vector lengths    */\n)\n{\n    SKP_int   i; \n    SKP_int64 sum = 0;\n    for( i = 0; i < len; i++ ) {\n        sum = SKP_SMLALBB( sum, inVec1[ i ], inVec2[ i ] );\n    }\n    return sum;\n}\n#endif\n"
  },
  {
    "path": "app/jni/SKP_Silk_interpolate.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n/* Interpolate two vectors */\nvoid SKP_Silk_interpolate(\n    SKP_int                         xi[ MAX_LPC_ORDER ],    /* O    interpolated vector                     */\n    const SKP_int                   x0[ MAX_LPC_ORDER ],    /* I    first vector                            */\n    const SKP_int                   x1[ MAX_LPC_ORDER ],    /* I    second vector                           */\n    const SKP_int                   ifact_Q2,               /* I    interp. factor, weight on 2nd vector    */\n    const SKP_int                   d                       /* I    number of parameters                    */\n)\n{\n    SKP_int i;\n\n    SKP_assert( ifact_Q2 >= 0 );\n    SKP_assert( ifact_Q2 <= ( 1 << 2 ) );\n\n    for( i = 0; i < d; i++ ) {\n        xi[ i ] = ( SKP_int )( ( SKP_int32 )x0[ i ] + SKP_RSHIFT( SKP_MUL( ( SKP_int32 )x1[ i ] - ( SKP_int32 )x0[ i ], ifact_Q2 ), 2 ) );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_k2a.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_k2a.c                                                     *\n *                                                                      *\n * Step up function, converts reflection coefficients to prediction     *\n * coefficients                                                         *\n *                                                                      *\n * Copyright 2008 (c), Skype Limited                                    *\n * Date: 080103                                                         *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Step up function, converts reflection coefficients to prediction coefficients */\nvoid SKP_Silk_k2a(\n    SKP_int32            *A_Q24,                 /* O:    Prediction coefficients [order] Q24         */\n    const SKP_int16      *rc_Q15,                /* I:    Reflection coefficients [order] Q15         */\n    const SKP_int32      order                   /* I:    Prediction order                            */\n)\n{\n    SKP_int   k, n;\n    SKP_int32 Atmp[ SKP_Silk_MAX_ORDER_LPC ];\n\n    for( k = 0; k < order; k++ ) {\n        for( n = 0; n < k; n++ ) {\n            Atmp[ n ] = A_Q24[ n ];\n        }\n        for( n = 0; n < k; n++ ) {\n            A_Q24[ n ] = SKP_SMLAWB( A_Q24[ n ], SKP_LSHIFT( Atmp[ k - n - 1 ], 1 ), rc_Q15[ k ] );\n        }\n        A_Q24[ k ] = -SKP_LSHIFT( (SKP_int32)rc_Q15[ k ], 9 );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_k2a_Q16.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_k2a.c                                                     *\n *                                                                      *\n * Step up function, converts reflection coefficients to prediction     *\n * coefficients                                                         *\n *                                                                      *\n * Copyright 2008 (c), Skype Limited                                    *\n * Date: 080103                                                         *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Step up function, converts reflection coefficients to prediction coefficients */\nvoid SKP_Silk_k2a_Q16(\n    SKP_int32            *A_Q24,                 /* O:    Prediction coefficients [order] Q24         */\n    const SKP_int32      *rc_Q16,                /* I:    Reflection coefficients [order] Q16         */\n    const SKP_int32      order                   /* I:    Prediction order                            */\n)\n{\n    SKP_int   k, n;\n    SKP_int32 Atmp[ SKP_Silk_MAX_ORDER_LPC ];\n\n    for( k = 0; k < order; k++ ) {\n        for( n = 0; n < k; n++ ) {\n            Atmp[ n ] = A_Q24[ n ];\n        }\n        for( n = 0; n < k; n++ ) {\n            A_Q24[ n ] = SKP_SMLAWW( A_Q24[ n ], Atmp[ k - n - 1 ], rc_Q16[ k ] );\n        }\n        A_Q24[ k ] = -SKP_LSHIFT( rc_Q16[ k ], 8 );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_lin2log.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_lin2log.c                                                 *\n *                                                                      *\n * Convert input to a log scale                                         *\n * Approximation of 128 * log2()                                        *\n *                                                                      *\n * Copyright 2006 (c), Skype Limited                                    *\n * Date: 060221                                                         *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n#if EMBEDDED_ARM<4\n/* Approximation of 128 * log2() (very close inverse of approx 2^() below) */\n/* Convert input to a log scale    */ \nSKP_int32 SKP_Silk_lin2log( const SKP_int32 inLin )    /* I:    Input in linear scale */\n{\n    SKP_int32 lz, frac_Q7;\n\n    SKP_Silk_CLZ_FRAC( inLin, &lz, &frac_Q7 );\n\n    /* Piece-wise parabolic approximation */\n    return( SKP_LSHIFT( 31 - lz, 7 ) + SKP_SMLAWB( frac_Q7, SKP_MUL( frac_Q7, 128 - frac_Q7 ), 179 ) );\n}\n#endif\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_log2lin.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_log2lin.c                                                 *\n *                                                                      *\n * Convert input to a linear scale                                      *\n *                                                                      *\n * Copyright 2006 (c), Skype Limited                                    *\n * Date: 060221                                                         *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Approximation of 2^() (very close inverse of SKP_Silk_lin2log()) */\n/* Convert input to a linear scale    */ \nSKP_int32 SKP_Silk_log2lin( const SKP_int32 inLog_Q7 )    /* I:    Input on log scale */ \n{\n    SKP_int32 out, frac_Q7;\n\n    if( inLog_Q7 < 0 ) {\n        return( 0 );\n    } else if( inLog_Q7 >= ( 31 << 7 ) ) {\n        /* Saturate, and prevent wrap-around */\n        return( SKP_int32_MAX );\n    }\n\n    out = SKP_LSHIFT( 1, SKP_RSHIFT( inLog_Q7, 7 ) );\n    frac_Q7 = inLog_Q7 & 0x7F;\n    if( inLog_Q7 < 2048 ) {\n        /* Piece-wise parabolic approximation */\n        out = SKP_ADD_RSHIFT( out, SKP_MUL( out, SKP_SMLAWB( frac_Q7, SKP_MUL( frac_Q7, 128 - frac_Q7 ), -174 ) ), 7 );\n    } else {\n        /* Piece-wise parabolic approximation */\n        out = SKP_MLA( out, SKP_RSHIFT( out, 7 ), SKP_SMLAWB( frac_Q7, SKP_MUL( frac_Q7, 128 - frac_Q7 ), -174 ) );\n    }\n    return out;\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_noise_shape_analysis_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n#include \"SKP_Silk_tuning_parameters.h\"\n\n/* Compute gain to make warped filter coefficients have a zero mean log frequency response on a     */\n/* non-warped frequency scale. (So that it can be implemented with a minimum-phase monic filter.)   */\nSKP_INLINE SKP_int32 warped_gain( // gain in Q16\n    const SKP_int32     *coefs_Q24, \n    SKP_int             lambda_Q16, \n    SKP_int             order \n) {\n    SKP_int   i;\n    SKP_int32 gain_Q24;\n\n    lambda_Q16 = -lambda_Q16;\n    gain_Q24 = coefs_Q24[ order - 1 ];\n    for( i = order - 2; i >= 0; i-- ) {\n        gain_Q24 = SKP_SMLAWB( coefs_Q24[ i ], gain_Q24, lambda_Q16 );\n    }\n    gain_Q24  = SKP_SMLAWB( SKP_FIX_CONST( 1.0, 24 ), gain_Q24, -lambda_Q16 );\n    return SKP_INVERSE32_varQ( gain_Q24, 40 );\n}\n\n/* Convert warped filter coefficients to monic pseudo-warped coefficients and limit maximum     */\n/* amplitude of monic warped coefficients by using bandwidth expansion on the true coefficients */\nSKP_INLINE void limit_warped_coefs( \n    SKP_int32           *coefs_syn_Q24,\n    SKP_int32           *coefs_ana_Q24,\n    SKP_int             lambda_Q16,\n    SKP_int32           limit_Q24,\n    SKP_int             order\n) {\n    SKP_int   i, iter, ind = 0;\n    SKP_int32 tmp, maxabs_Q24, chirp_Q16, gain_syn_Q16, gain_ana_Q16;\n    SKP_int32 nom_Q16, den_Q24;\n\n    /* Convert to monic coefficients */\n    lambda_Q16 = -lambda_Q16;\n    for( i = order - 1; i > 0; i-- ) {\n        coefs_syn_Q24[ i - 1 ] = SKP_SMLAWB( coefs_syn_Q24[ i - 1 ], coefs_syn_Q24[ i ], lambda_Q16 );\n        coefs_ana_Q24[ i - 1 ] = SKP_SMLAWB( coefs_ana_Q24[ i - 1 ], coefs_ana_Q24[ i ], lambda_Q16 );\n    }\n    lambda_Q16 = -lambda_Q16;\n    nom_Q16  = SKP_SMLAWB( SKP_FIX_CONST( 1.0, 16 ), -lambda_Q16,        lambda_Q16 );\n    den_Q24  = SKP_SMLAWB( SKP_FIX_CONST( 1.0, 24 ), coefs_syn_Q24[ 0 ], lambda_Q16 );\n    gain_syn_Q16 = SKP_DIV32_varQ( nom_Q16, den_Q24, 24 );\n    den_Q24  = SKP_SMLAWB( SKP_FIX_CONST( 1.0, 24 ), coefs_ana_Q24[ 0 ], lambda_Q16 );\n    gain_ana_Q16 = SKP_DIV32_varQ( nom_Q16, den_Q24, 24 );\n    for( i = 0; i < order; i++ ) {\n        coefs_syn_Q24[ i ] = SKP_SMULWW( gain_syn_Q16, coefs_syn_Q24[ i ] );\n        coefs_ana_Q24[ i ] = SKP_SMULWW( gain_ana_Q16, coefs_ana_Q24[ i ] );\n    }\n\n    for( iter = 0; iter < 10; iter++ ) {\n        /* Find maximum absolute value */\n        maxabs_Q24 = -1;\n        for( i = 0; i < order; i++ ) {\n            tmp = SKP_max( SKP_abs_int32( coefs_syn_Q24[ i ] ), SKP_abs_int32( coefs_ana_Q24[ i ] ) );\n            if( tmp > maxabs_Q24 ) {\n                maxabs_Q24 = tmp;\n                ind = i;\n            }\n        }\n        if( maxabs_Q24 <= limit_Q24 ) {\n            /* Coefficients are within range - done */\n            return;\n        }\n\n        /* Convert back to true warped coefficients */\n        for( i = 1; i < order; i++ ) {\n            coefs_syn_Q24[ i - 1 ] = SKP_SMLAWB( coefs_syn_Q24[ i - 1 ], coefs_syn_Q24[ i ], lambda_Q16 );\n            coefs_ana_Q24[ i - 1 ] = SKP_SMLAWB( coefs_ana_Q24[ i - 1 ], coefs_ana_Q24[ i ], lambda_Q16 );\n        }\n        gain_syn_Q16 = SKP_INVERSE32_varQ( gain_syn_Q16, 32 );\n        gain_ana_Q16 = SKP_INVERSE32_varQ( gain_ana_Q16, 32 );\n        for( i = 0; i < order; i++ ) {\n            coefs_syn_Q24[ i ] = SKP_SMULWW( gain_syn_Q16, coefs_syn_Q24[ i ] );\n            coefs_ana_Q24[ i ] = SKP_SMULWW( gain_ana_Q16, coefs_ana_Q24[ i ] );\n        }\n\n        /* Apply bandwidth expansion */\n        chirp_Q16 = SKP_FIX_CONST( 0.99, 16 ) - SKP_DIV32_varQ(\n            SKP_SMULWB( maxabs_Q24 - limit_Q24, SKP_SMLABB( SKP_FIX_CONST( 0.8, 10 ), SKP_FIX_CONST( 0.1, 10 ), iter ) ), \n            SKP_MUL( maxabs_Q24, ind + 1 ), 22 );\n        SKP_Silk_bwexpander_32( coefs_syn_Q24, order, chirp_Q16 );\n        SKP_Silk_bwexpander_32( coefs_ana_Q24, order, chirp_Q16 );\n\n        /* Convert to monic warped coefficients */\n        lambda_Q16 = -lambda_Q16;\n        for( i = order - 1; i > 0; i-- ) {\n            coefs_syn_Q24[ i - 1 ] = SKP_SMLAWB( coefs_syn_Q24[ i - 1 ], coefs_syn_Q24[ i ], lambda_Q16 );\n            coefs_ana_Q24[ i - 1 ] = SKP_SMLAWB( coefs_ana_Q24[ i - 1 ], coefs_ana_Q24[ i ], lambda_Q16 );\n        }\n        lambda_Q16 = -lambda_Q16;\n        nom_Q16  = SKP_SMLAWB( SKP_FIX_CONST( 1.0, 16 ), -lambda_Q16,        lambda_Q16 );\n        den_Q24  = SKP_SMLAWB( SKP_FIX_CONST( 1.0, 24 ), coefs_syn_Q24[ 0 ], lambda_Q16 );\n        gain_syn_Q16 = SKP_DIV32_varQ( nom_Q16, den_Q24, 24 );\n        den_Q24  = SKP_SMLAWB( SKP_FIX_CONST( 1.0, 24 ), coefs_ana_Q24[ 0 ], lambda_Q16 );\n        gain_ana_Q16 = SKP_DIV32_varQ( nom_Q16, den_Q24, 24 );\n        for( i = 0; i < order; i++ ) {\n            coefs_syn_Q24[ i ] = SKP_SMULWW( gain_syn_Q16, coefs_syn_Q24[ i ] );\n            coefs_ana_Q24[ i ] = SKP_SMULWW( gain_ana_Q16, coefs_ana_Q24[ i ] );\n        }\n    }\n\tSKP_assert( 0 );\n}\n\n/**************************************************************/\n/* Compute noise shaping coefficients and initial gain values */\n/**************************************************************/\nvoid SKP_Silk_noise_shape_analysis_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,         /* I/O  Encoder state FIX                           */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl,     /* I/O  Encoder control FIX                         */\n    const SKP_int16                 *pitch_res,     /* I    LPC residual from pitch analysis            */\n    const SKP_int16                 *x              /* I    Input signal [ frame_length + la_shape ]    */\n)\n{\n    SKP_Silk_shape_state_FIX *psShapeSt = &psEnc->sShape;\n    SKP_int     k, i, nSamples, Qnrg, b_Q14, warping_Q16, scale = 0;\n    SKP_int32   SNR_adj_dB_Q7, HarmBoost_Q16, HarmShapeGain_Q16, Tilt_Q16, tmp32;\n    SKP_int32   nrg, pre_nrg_Q30, log_energy_Q7, log_energy_prev_Q7, energy_variation_Q7;\n    SKP_int32   delta_Q16, BWExp1_Q16, BWExp2_Q16, gain_mult_Q16, gain_add_Q16, strength_Q16, b_Q8;\n    SKP_int32   auto_corr[     MAX_SHAPE_LPC_ORDER + 1 ];\n    SKP_int32   refl_coef_Q16[ MAX_SHAPE_LPC_ORDER ];\n    SKP_int32   AR1_Q24[       MAX_SHAPE_LPC_ORDER ];\n    SKP_int32   AR2_Q24[       MAX_SHAPE_LPC_ORDER ];\n    SKP_int16   x_windowed[    SHAPE_LPC_WIN_MAX ];\n    const SKP_int16 *x_ptr, *pitch_res_ptr;\n\n    /* Point to start of first LPC analysis block */\n    x_ptr = x - psEnc->sCmn.la_shape;\n\n    /****************/\n    /* CONTROL SNR  */\n    /****************/\n    /* Reduce SNR_dB values if recent bitstream has exceeded TargetRate */\n    psEncCtrl->current_SNR_dB_Q7 = psEnc->SNR_dB_Q7 - SKP_SMULWB( SKP_LSHIFT( ( SKP_int32 )psEnc->BufferedInChannel_ms, 7 ), \n        SKP_FIX_CONST( 0.05, 16 ) );\n\n    /* Reduce SNR_dB if inband FEC used */\n    if( psEnc->speech_activity_Q8 > SKP_FIX_CONST( LBRR_SPEECH_ACTIVITY_THRES, 8 ) ) {\n        psEncCtrl->current_SNR_dB_Q7 -= SKP_RSHIFT( psEnc->inBandFEC_SNR_comp_Q8, 1 );\n    }\n\n    /****************/\n    /* GAIN CONTROL */\n    /****************/\n    /* Input quality is the average of the quality in the lowest two VAD bands */\n    psEncCtrl->input_quality_Q14 = ( SKP_int )SKP_RSHIFT( ( SKP_int32 )psEncCtrl->input_quality_bands_Q15[ 0 ] \n        + psEncCtrl->input_quality_bands_Q15[ 1 ], 2 );\n\n    /* Coding quality level, between 0.0_Q0 and 1.0_Q0, but in Q14 */\n    psEncCtrl->coding_quality_Q14 = SKP_RSHIFT( SKP_Silk_sigm_Q15( SKP_RSHIFT_ROUND( psEncCtrl->current_SNR_dB_Q7 - \n        SKP_FIX_CONST( 18.0, 7 ), 4 ) ), 1 );\n\n    /* Reduce coding SNR during low speech activity */\n    b_Q8 = SKP_FIX_CONST( 1.0, 8 ) - psEnc->speech_activity_Q8;\n    b_Q8 = SKP_SMULWB( SKP_LSHIFT( b_Q8, 8 ), b_Q8 );\n    SNR_adj_dB_Q7 = SKP_SMLAWB( psEncCtrl->current_SNR_dB_Q7,\n        SKP_SMULBB( SKP_FIX_CONST( -BG_SNR_DECR_dB, 7 ) >> ( 4 + 1 ), b_Q8 ),                                       // Q11\n        SKP_SMULWB( SKP_FIX_CONST( 1.0, 14 ) + psEncCtrl->input_quality_Q14, psEncCtrl->coding_quality_Q14 ) );     // Q12\n\n    if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) {\n        /* Reduce gains for periodic signals */\n        SNR_adj_dB_Q7 = SKP_SMLAWB( SNR_adj_dB_Q7, SKP_FIX_CONST( HARM_SNR_INCR_dB, 8 ), psEnc->LTPCorr_Q15 );\n    } else { \n        /* For unvoiced signals and low-quality input, adjust the quality slower than SNR_dB setting */\n        SNR_adj_dB_Q7 = SKP_SMLAWB( SNR_adj_dB_Q7, \n            SKP_SMLAWB( SKP_FIX_CONST( 6.0, 9 ), -SKP_FIX_CONST( 0.4, 18 ), psEncCtrl->current_SNR_dB_Q7 ),\n            SKP_FIX_CONST( 1.0, 14 ) - psEncCtrl->input_quality_Q14 );\n    }\n\n    /*************************/\n    /* SPARSENESS PROCESSING */\n    /*************************/\n    /* Set quantizer offset */\n    if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) {\n        /* Initally set to 0; may be overruled in process_gains(..) */\n        psEncCtrl->sCmn.QuantOffsetType = 0;\n        psEncCtrl->sparseness_Q8 = 0;\n    } else {\n        /* Sparseness measure, based on relative fluctuations of energy per 2 milliseconds */\n        nSamples = SKP_LSHIFT( psEnc->sCmn.fs_kHz, 1 );\n        energy_variation_Q7 = 0;\n        log_energy_prev_Q7  = 0;\n        pitch_res_ptr = pitch_res;\n        for( k = 0; k < FRAME_LENGTH_MS / 2; k++ ) {    \n            SKP_Silk_sum_sqr_shift( &nrg, &scale, pitch_res_ptr, nSamples );\n            nrg += SKP_RSHIFT( nSamples, scale );           // Q(-scale)\n            \n            log_energy_Q7 = SKP_Silk_lin2log( nrg );\n            if( k > 0 ) {\n                energy_variation_Q7 += SKP_abs( log_energy_Q7 - log_energy_prev_Q7 );\n            }\n            log_energy_prev_Q7 = log_energy_Q7;\n            pitch_res_ptr += nSamples;\n        }\n\n        psEncCtrl->sparseness_Q8 = SKP_RSHIFT( SKP_Silk_sigm_Q15( SKP_SMULWB( energy_variation_Q7 - \n            SKP_FIX_CONST( 5.0, 7 ), SKP_FIX_CONST( 0.1, 16 ) ) ), 7 );\n\n        /* Set quantization offset depending on sparseness measure */\n        if( psEncCtrl->sparseness_Q8 > SKP_FIX_CONST( SPARSENESS_THRESHOLD_QNT_OFFSET, 8 ) ) {\n            psEncCtrl->sCmn.QuantOffsetType = 0;\n        } else {\n            psEncCtrl->sCmn.QuantOffsetType = 1;\n        }\n        \n        /* Increase coding SNR for sparse signals */\n        SNR_adj_dB_Q7 = SKP_SMLAWB( SNR_adj_dB_Q7, SKP_FIX_CONST( SPARSE_SNR_INCR_dB, 15 ), psEncCtrl->sparseness_Q8 - SKP_FIX_CONST( 0.5, 8 ) );\n    }\n\n    /*******************************/\n    /* Control bandwidth expansion */\n    /*******************************/\n    /* More BWE for signals with high prediction gain */\n    strength_Q16 = SKP_SMULWB( psEncCtrl->predGain_Q16, SKP_FIX_CONST( FIND_PITCH_WHITE_NOISE_FRACTION, 16 ) );\n    BWExp1_Q16 = BWExp2_Q16 = SKP_DIV32_varQ( SKP_FIX_CONST( BANDWIDTH_EXPANSION, 16 ), \n        SKP_SMLAWW( SKP_FIX_CONST( 1.0, 16 ), strength_Q16, strength_Q16 ), 16 );\n    delta_Q16  = SKP_SMULWB( SKP_FIX_CONST( 1.0, 16 ) - SKP_SMULBB( 3, psEncCtrl->coding_quality_Q14 ), \n        SKP_FIX_CONST( LOW_RATE_BANDWIDTH_EXPANSION_DELTA, 16 ) );\n    BWExp1_Q16 = SKP_SUB32( BWExp1_Q16, delta_Q16 );\n    BWExp2_Q16 = SKP_ADD32( BWExp2_Q16, delta_Q16 );\n    /* BWExp1 will be applied after BWExp2, so make it relative */\n    BWExp1_Q16 = SKP_DIV32_16( SKP_LSHIFT( BWExp1_Q16, 14 ), SKP_RSHIFT( BWExp2_Q16, 2 ) );\n\n    if( psEnc->sCmn.warping_Q16 > 0 ) {\n        /* Slightly more warping in analysis will move quantization noise up in frequency, where it's better masked */\n        warping_Q16 = SKP_SMLAWB( psEnc->sCmn.warping_Q16, psEncCtrl->coding_quality_Q14, SKP_FIX_CONST( 0.01, 18 ) );\n    } else {\n        warping_Q16 = 0;\n    }\n\n    /********************************************/\n    /* Compute noise shaping AR coefs and gains */\n    /********************************************/\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        /* Apply window: sine slope followed by flat part followed by cosine slope */\n        SKP_int shift, slope_part, flat_part;\n        flat_part = psEnc->sCmn.fs_kHz * 5;\n        slope_part = SKP_RSHIFT( psEnc->sCmn.shapeWinLength - flat_part, 1 );\n\n        SKP_Silk_apply_sine_window( x_windowed, x_ptr, 1, slope_part );\n        shift = slope_part;\n        SKP_memcpy( x_windowed + shift, x_ptr + shift, flat_part * sizeof(SKP_int16) );\n        shift += flat_part;\n        SKP_Silk_apply_sine_window( x_windowed + shift, x_ptr + shift, 2, slope_part );\n        \n        /* Update pointer: next LPC analysis block */\n        x_ptr += psEnc->sCmn.subfr_length;\n\n        if( psEnc->sCmn.warping_Q16 > 0 ) {\n            /* Calculate warped auto correlation */\n            SKP_Silk_warped_autocorrelation_FIX( auto_corr, &scale, x_windowed, warping_Q16, psEnc->sCmn.shapeWinLength, psEnc->sCmn.shapingLPCOrder ); \n        } else {\n            /* Calculate regular auto correlation */\n            SKP_Silk_autocorr( auto_corr, &scale, x_windowed, psEnc->sCmn.shapeWinLength, psEnc->sCmn.shapingLPCOrder + 1 );\n        }\n\n        /* Add white noise, as a fraction of energy */\n        auto_corr[0] = SKP_ADD32( auto_corr[0], SKP_max_32( SKP_SMULWB( SKP_RSHIFT( auto_corr[ 0 ], 4 ), \n            SKP_FIX_CONST( SHAPE_WHITE_NOISE_FRACTION, 20 ) ), 1 ) ); \n\n        /* Calculate the reflection coefficients using schur */\n        nrg = SKP_Silk_schur64( refl_coef_Q16, auto_corr, psEnc->sCmn.shapingLPCOrder );\n        SKP_assert( nrg >= 0 );\n\n        /* Convert reflection coefficients to prediction coefficients */\n        SKP_Silk_k2a_Q16( AR2_Q24, refl_coef_Q16, psEnc->sCmn.shapingLPCOrder );\n\n        Qnrg = -scale;          // range: -12...30\n        SKP_assert( Qnrg >= -12 );\n        SKP_assert( Qnrg <=  30 );\n\n        /* Make sure that Qnrg is an even number */\n        if( Qnrg & 1 ) {\n            Qnrg -= 1;\n            nrg >>= 1;\n        }\n\n        tmp32 = SKP_Silk_SQRT_APPROX( nrg );\n        Qnrg >>= 1;             // range: -6...15\n\n        psEncCtrl->Gains_Q16[ k ] = SKP_LSHIFT_SAT32( tmp32, 16 - Qnrg );\n\n        if( psEnc->sCmn.warping_Q16 > 0 ) {\n            /* Adjust gain for warping */\n            gain_mult_Q16 = warped_gain( AR2_Q24, warping_Q16, psEnc->sCmn.shapingLPCOrder );\n            SKP_assert( psEncCtrl->Gains_Q16[ k ] >= 0 );\n            psEncCtrl->Gains_Q16[ k ] = SKP_SMULWW( psEncCtrl->Gains_Q16[ k ], gain_mult_Q16 );\n            if( psEncCtrl->Gains_Q16[ k ] < 0 ) {\n                psEncCtrl->Gains_Q16[ k ] = SKP_int32_MAX;\n            }\n        }\n\n        /* Bandwidth expansion for synthesis filter shaping */\n        SKP_Silk_bwexpander_32( AR2_Q24, psEnc->sCmn.shapingLPCOrder, BWExp2_Q16 );\n\n        /* Compute noise shaping filter coefficients */\n        SKP_memcpy( AR1_Q24, AR2_Q24, psEnc->sCmn.shapingLPCOrder * sizeof( SKP_int32 ) );\n\n        /* Bandwidth expansion for analysis filter shaping */\n        SKP_assert( BWExp1_Q16 <= SKP_FIX_CONST( 1.0, 16 ) );\n        SKP_Silk_bwexpander_32( AR1_Q24, psEnc->sCmn.shapingLPCOrder, BWExp1_Q16 );\n\n        /* Ratio of prediction gains, in energy domain */\n        SKP_Silk_LPC_inverse_pred_gain_Q24( &pre_nrg_Q30, AR2_Q24, psEnc->sCmn.shapingLPCOrder );\n        SKP_Silk_LPC_inverse_pred_gain_Q24( &nrg,         AR1_Q24, psEnc->sCmn.shapingLPCOrder );\n\n        //psEncCtrl->GainsPre[ k ] = 1.0f - 0.7f * ( 1.0f - pre_nrg / nrg ) = 0.3f + 0.7f * pre_nrg / nrg;\n        pre_nrg_Q30 = SKP_LSHIFT32( SKP_SMULWB( pre_nrg_Q30, SKP_FIX_CONST( 0.7, 15 ) ), 1 );\n        psEncCtrl->GainsPre_Q14[ k ] = ( SKP_int ) SKP_FIX_CONST( 0.3, 14 ) + SKP_DIV32_varQ( pre_nrg_Q30, nrg, 14 );\n\n        /* Convert to monic warped prediction coefficients and limit absolute values */\n        limit_warped_coefs( AR2_Q24, AR1_Q24, warping_Q16, SKP_FIX_CONST( 3.999, 24 ), psEnc->sCmn.shapingLPCOrder );\n\n        /* Convert from Q24 to Q13 and store in int16 */\n        for( i = 0; i < psEnc->sCmn.shapingLPCOrder; i++ ) {\n            psEncCtrl->AR1_Q13[ k * MAX_SHAPE_LPC_ORDER + i ] = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( AR1_Q24[ i ], 11 ) );\n            psEncCtrl->AR2_Q13[ k * MAX_SHAPE_LPC_ORDER + i ] = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( AR2_Q24[ i ], 11 ) );\n        }\n    }\n\n    /*****************/\n    /* Gain tweaking */\n    /*****************/\n    /* Increase gains during low speech activity and put lower limit on gains */\n    gain_mult_Q16 = SKP_Silk_log2lin( -SKP_SMLAWB( -SKP_FIX_CONST( 16.0, 7 ), SNR_adj_dB_Q7,                            SKP_FIX_CONST( 0.16, 16 ) ) );\n    gain_add_Q16  = SKP_Silk_log2lin(  SKP_SMLAWB(  SKP_FIX_CONST( 16.0, 7 ), SKP_FIX_CONST( NOISE_FLOOR_dB, 7 ),       SKP_FIX_CONST( 0.16, 16 ) ) );\n    tmp32         = SKP_Silk_log2lin(  SKP_SMLAWB(  SKP_FIX_CONST( 16.0, 7 ), SKP_FIX_CONST( RELATIVE_MIN_GAIN_dB, 7 ), SKP_FIX_CONST( 0.16, 16 ) ) );\n    tmp32 = SKP_SMULWW( psEnc->avgGain_Q16, tmp32 );\n    gain_add_Q16 = SKP_ADD_SAT32( gain_add_Q16, tmp32 );\n    SKP_assert( gain_mult_Q16 >= 0 );\n\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        psEncCtrl->Gains_Q16[ k ] = SKP_SMULWW( psEncCtrl->Gains_Q16[ k ], gain_mult_Q16 );\n        if( psEncCtrl->Gains_Q16[ k ] < 0 ) {\n            psEncCtrl->Gains_Q16[ k ] = SKP_int32_MAX;\n        }\n    }\n\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        psEncCtrl->Gains_Q16[ k ] = SKP_ADD_POS_SAT32( psEncCtrl->Gains_Q16[ k ], gain_add_Q16 );\n        psEnc->avgGain_Q16 = SKP_ADD_SAT32( \n            psEnc->avgGain_Q16, \n            SKP_SMULWB(\n                psEncCtrl->Gains_Q16[ k ] - psEnc->avgGain_Q16, \n                SKP_RSHIFT_ROUND( SKP_SMULBB( psEnc->speech_activity_Q8, SKP_FIX_CONST( GAIN_SMOOTHING_COEF, 10 ) ), 2 ) \n            ) );\n    }\n\n    /************************************************/\n    /* Decrease level during fricatives (de-essing) */\n    /************************************************/\n    gain_mult_Q16 = SKP_FIX_CONST( 1.0, 16 ) + SKP_RSHIFT_ROUND( SKP_MLA( SKP_FIX_CONST( INPUT_TILT, 26 ), \n        psEncCtrl->coding_quality_Q14, SKP_FIX_CONST( HIGH_RATE_INPUT_TILT, 12 ) ), 10 );\n\n    if( psEncCtrl->input_tilt_Q15 <= 0 && psEncCtrl->sCmn.sigtype == SIG_TYPE_UNVOICED ) {\n        if( psEnc->sCmn.fs_kHz == 24 ) {\n            SKP_int32 essStrength_Q15 = SKP_SMULWW( -psEncCtrl->input_tilt_Q15, \n                SKP_SMULBB( psEnc->speech_activity_Q8, SKP_FIX_CONST( 1.0, 8 ) - psEncCtrl->sparseness_Q8 ) );\n            tmp32 = SKP_Silk_log2lin( SKP_FIX_CONST( 16.0, 7 ) - SKP_SMULWB( essStrength_Q15, \n                SKP_SMULWB( SKP_FIX_CONST( DE_ESSER_COEF_SWB_dB, 7 ), SKP_FIX_CONST( 0.16, 17 ) ) ) );\n            gain_mult_Q16 = SKP_SMULWW( gain_mult_Q16, tmp32 );\n        } else if( psEnc->sCmn.fs_kHz == 16 ) {\n            SKP_int32 essStrength_Q15 = SKP_SMULWW(-psEncCtrl->input_tilt_Q15, \n                SKP_SMULBB( psEnc->speech_activity_Q8, SKP_FIX_CONST( 1.0, 8 ) - psEncCtrl->sparseness_Q8 ));\n            tmp32 = SKP_Silk_log2lin( SKP_FIX_CONST( 16.0, 7 ) - SKP_SMULWB( essStrength_Q15, \n                SKP_SMULWB( SKP_FIX_CONST( DE_ESSER_COEF_WB_dB, 7 ), SKP_FIX_CONST( 0.16, 17 ) ) ) );\n            gain_mult_Q16 = SKP_SMULWW( gain_mult_Q16, tmp32 );\n        } else {\n            SKP_assert( psEnc->sCmn.fs_kHz == 12 || psEnc->sCmn.fs_kHz == 8 );\n        }\n    }\n\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        psEncCtrl->GainsPre_Q14[ k ] = SKP_SMULWB( gain_mult_Q16, psEncCtrl->GainsPre_Q14[ k ] );\n    }\n\n    /************************************************/\n    /* Control low-frequency shaping and noise tilt */\n    /************************************************/\n    /* Less low frequency shaping for noisy inputs */\n    strength_Q16 = SKP_MUL( SKP_FIX_CONST( LOW_FREQ_SHAPING, 0 ), SKP_FIX_CONST( 1.0, 16 ) + \n        SKP_SMULBB( SKP_FIX_CONST( LOW_QUALITY_LOW_FREQ_SHAPING_DECR, 1 ), psEncCtrl->input_quality_bands_Q15[ 0 ] - SKP_FIX_CONST( 1.0, 15 ) ) );\n    if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) {\n        /* Reduce low frequencies quantization noise for periodic signals, depending on pitch lag */\n        /*f = 400; freqz([1, -0.98 + 2e-4 * f], [1, -0.97 + 7e-4 * f], 2^12, Fs); axis([0, 1000, -10, 1])*/\n        SKP_int fs_kHz_inv = SKP_DIV32_16( SKP_FIX_CONST( 0.2, 14 ), psEnc->sCmn.fs_kHz );\n        for( k = 0; k < NB_SUBFR; k++ ) {\n            b_Q14 = fs_kHz_inv + SKP_DIV32_16( SKP_FIX_CONST( 3.0, 14 ), psEncCtrl->sCmn.pitchL[ k ] ); \n            /* Pack two coefficients in one int32 */\n            psEncCtrl->LF_shp_Q14[ k ]  = SKP_LSHIFT( SKP_FIX_CONST( 1.0, 14 ) - b_Q14 - SKP_SMULWB( strength_Q16, b_Q14 ), 16 );\n            psEncCtrl->LF_shp_Q14[ k ] |= (SKP_uint16)( b_Q14 - SKP_FIX_CONST( 1.0, 14 ) );\n        }\n        SKP_assert( SKP_FIX_CONST( HARM_HP_NOISE_COEF, 24 ) < SKP_FIX_CONST( 0.5, 24 ) ); // Guarantees that second argument to SMULWB() is within range of an SKP_int16\n        Tilt_Q16 = - SKP_FIX_CONST( HP_NOISE_COEF, 16 ) - \n            SKP_SMULWB( SKP_FIX_CONST( 1.0, 16 ) - SKP_FIX_CONST( HP_NOISE_COEF, 16 ), \n                SKP_SMULWB( SKP_FIX_CONST( HARM_HP_NOISE_COEF, 24 ), psEnc->speech_activity_Q8 ) );\n    } else {\n        b_Q14 = SKP_DIV32_16( 21299, psEnc->sCmn.fs_kHz ); // 1.3_Q0 = 21299_Q14\n        /* Pack two coefficients in one int32 */\n        psEncCtrl->LF_shp_Q14[ 0 ]  = SKP_LSHIFT( SKP_FIX_CONST( 1.0, 14 ) - b_Q14 - \n            SKP_SMULWB( strength_Q16, SKP_SMULWB( SKP_FIX_CONST( 0.6, 16 ), b_Q14 ) ), 16 );\n        psEncCtrl->LF_shp_Q14[ 0 ] |= (SKP_uint16)( b_Q14 - SKP_FIX_CONST( 1.0, 14 ) );\n        for( k = 1; k < NB_SUBFR; k++ ) {\n            psEncCtrl->LF_shp_Q14[ k ] = psEncCtrl->LF_shp_Q14[ 0 ];\n        }\n        Tilt_Q16 = -SKP_FIX_CONST( HP_NOISE_COEF, 16 );\n    }\n\n    /****************************/\n    /* HARMONIC SHAPING CONTROL */\n    /****************************/\n    /* Control boosting of harmonic frequencies */\n    HarmBoost_Q16 = SKP_SMULWB( SKP_SMULWB( SKP_FIX_CONST( 1.0, 17 ) - SKP_LSHIFT( psEncCtrl->coding_quality_Q14, 3 ), \n        psEnc->LTPCorr_Q15 ), SKP_FIX_CONST( LOW_RATE_HARMONIC_BOOST, 16 ) );\n\n    /* More harmonic boost for noisy input signals */\n    HarmBoost_Q16 = SKP_SMLAWB( HarmBoost_Q16, \n        SKP_FIX_CONST( 1.0, 16 ) - SKP_LSHIFT( psEncCtrl->input_quality_Q14, 2 ), SKP_FIX_CONST( LOW_INPUT_QUALITY_HARMONIC_BOOST, 16 ) );\n\n    if( USE_HARM_SHAPING && psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) {\n        /* More harmonic noise shaping for high bitrates or noisy input */\n        HarmShapeGain_Q16 = SKP_SMLAWB( SKP_FIX_CONST( HARMONIC_SHAPING, 16 ), \n                SKP_FIX_CONST( 1.0, 16 ) - SKP_SMULWB( SKP_FIX_CONST( 1.0, 18 ) - SKP_LSHIFT( psEncCtrl->coding_quality_Q14, 4 ),\n                psEncCtrl->input_quality_Q14 ), SKP_FIX_CONST( HIGH_RATE_OR_LOW_QUALITY_HARMONIC_SHAPING, 16 ) );\n\n        /* Less harmonic noise shaping for less periodic signals */\n        HarmShapeGain_Q16 = SKP_SMULWB( SKP_LSHIFT( HarmShapeGain_Q16, 1 ), \n            SKP_Silk_SQRT_APPROX( SKP_LSHIFT( psEnc->LTPCorr_Q15, 15 ) ) );\n    } else {\n        HarmShapeGain_Q16 = 0;\n    }\n\n    /*************************/\n    /* Smooth over subframes */\n    /*************************/\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        psShapeSt->HarmBoost_smth_Q16 =\n            SKP_SMLAWB( psShapeSt->HarmBoost_smth_Q16,     HarmBoost_Q16     - psShapeSt->HarmBoost_smth_Q16,     SKP_FIX_CONST( SUBFR_SMTH_COEF, 16 ) );\n        psShapeSt->HarmShapeGain_smth_Q16 =\n            SKP_SMLAWB( psShapeSt->HarmShapeGain_smth_Q16, HarmShapeGain_Q16 - psShapeSt->HarmShapeGain_smth_Q16, SKP_FIX_CONST( SUBFR_SMTH_COEF, 16 ) );\n        psShapeSt->Tilt_smth_Q16 =\n            SKP_SMLAWB( psShapeSt->Tilt_smth_Q16,          Tilt_Q16          - psShapeSt->Tilt_smth_Q16,          SKP_FIX_CONST( SUBFR_SMTH_COEF, 16 ) );\n\n        psEncCtrl->HarmBoost_Q14[ k ]     = ( SKP_int )SKP_RSHIFT_ROUND( psShapeSt->HarmBoost_smth_Q16,     2 );\n        psEncCtrl->HarmShapeGain_Q14[ k ] = ( SKP_int )SKP_RSHIFT_ROUND( psShapeSt->HarmShapeGain_smth_Q16, 2 );\n        psEncCtrl->Tilt_Q14[ k ]          = ( SKP_int )SKP_RSHIFT_ROUND( psShapeSt->Tilt_smth_Q16,          2 );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_pitch_analysis_core.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/***********************************************************\n* Pitch analyser function\n********************************************************** */\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_pitch_est_defines.h\"\n#include \"SKP_Silk_common_pitch_est_defines.h\"\n\n#define SCRATCH_SIZE    22\n\n/************************************************************/\n/* Internally used functions                                */\n/************************************************************/\nvoid SKP_FIX_P_Ana_calc_corr_st3(\n    SKP_int32        cross_corr_st3[PITCH_EST_NB_SUBFR][PITCH_EST_NB_CBKS_STAGE3_MAX][PITCH_EST_NB_STAGE3_LAGS],/* (O) 3 DIM correlation array */\n    const SKP_int16  signal[],                        /* I vector to correlate         */\n    SKP_int          start_lag,                       /* I lag offset to search around */\n    SKP_int          sf_length,                       /* I length of a 5 ms subframe   */\n    SKP_int          complexity                       /* I Complexity setting          */\n);\n\nvoid SKP_FIX_P_Ana_calc_energy_st3(\n    SKP_int32        energies_st3[PITCH_EST_NB_SUBFR][PITCH_EST_NB_CBKS_STAGE3_MAX][PITCH_EST_NB_STAGE3_LAGS],/* (O) 3 DIM energy array */\n    const SKP_int16  signal[],                        /* I vector to calc energy in    */\n    SKP_int          start_lag,                       /* I lag offset to search around */\n    SKP_int          sf_length,                       /* I length of one 5 ms subframe */\n    SKP_int          complexity                       /* I Complexity setting          */\n);\n\nSKP_int32 SKP_FIX_P_Ana_find_scaling(\n    const SKP_int16  *signal,\n    const SKP_int    signal_length, \n    const SKP_int    sum_sqr_len\n);\n\n/*************************************************************/\n/*      FIXED POINT CORE PITCH ANALYSIS FUNCTION             */\n/*************************************************************/\nSKP_int SKP_Silk_pitch_analysis_core(  /* O    Voicing estimate: 0 voiced, 1 unvoiced                      */\n    const SKP_int16  *signal,            /* I    Signal of length PITCH_EST_FRAME_LENGTH_MS*Fs_kHz           */\n    SKP_int          *pitch_out,         /* O    4 pitch lag values                                          */\n    SKP_int          *lagIndex,          /* O    Lag Index                                                   */\n    SKP_int          *contourIndex,      /* O    Pitch contour Index                                         */\n    SKP_int          *LTPCorr_Q15,       /* I/O  Normalized correlation; input: value from previous frame    */\n    SKP_int          prevLag,            /* I    Last lag of previous frame; set to zero is unvoiced         */\n    const SKP_int32  search_thres1_Q16,  /* I    First stage threshold for lag candidates 0 - 1              */\n    const SKP_int    search_thres2_Q15,  /* I    Final threshold for lag candidates 0 - 1                    */\n    const SKP_int    Fs_kHz,             /* I    Sample frequency (kHz)                                      */\n    const SKP_int    complexity,         /* I   Complexity setting, 0-2, where 2 is highest                 */\n\tconst SKP_int\t forLJC\t\t\t     /* I\t 1 if this function is called from LJC code, 0 otherwise.  */\n)\n{\n    SKP_int16 signal_8kHz[ PITCH_EST_MAX_FRAME_LENGTH_ST_2 ];\n    SKP_int16 signal_4kHz[ PITCH_EST_MAX_FRAME_LENGTH_ST_1 ];\n    SKP_int32 scratch_mem[ 3 * PITCH_EST_MAX_FRAME_LENGTH ];\n    SKP_int16 *input_signal_ptr;\n    SKP_int32 filt_state[ PITCH_EST_MAX_DECIMATE_STATE_LENGTH ];\n    SKP_int   i, k, d, j;\n    SKP_int16 C[ PITCH_EST_NB_SUBFR ][ ( PITCH_EST_MAX_LAG >> 1 ) + 5 ];\n    const SKP_int16 *target_ptr, *basis_ptr;\n    SKP_int32 cross_corr, normalizer, energy, shift, energy_basis, energy_target;\n    SKP_int   d_srch[ PITCH_EST_D_SRCH_LENGTH ];\n    SKP_int16 d_comp[ ( PITCH_EST_MAX_LAG >> 1 ) + 5 ];\n    SKP_int   Cmax, length_d_srch, length_d_comp;\n    SKP_int32 sum, threshold, temp32;\n    SKP_int   CBimax, CBimax_new, CBimax_old, lag, start_lag, end_lag, lag_new;\n    SKP_int32 CC[ PITCH_EST_NB_CBKS_STAGE2_EXT ], CCmax, CCmax_b, CCmax_new_b, CCmax_new;\n    SKP_int32 energies_st3[  PITCH_EST_NB_SUBFR ][ PITCH_EST_NB_CBKS_STAGE3_MAX ][ PITCH_EST_NB_STAGE3_LAGS ];\n    SKP_int32 crosscorr_st3[ PITCH_EST_NB_SUBFR ][ PITCH_EST_NB_CBKS_STAGE3_MAX ][ PITCH_EST_NB_STAGE3_LAGS ];\n    SKP_int32 lag_counter;\n    SKP_int   frame_length, frame_length_8kHz, frame_length_4kHz, max_sum_sq_length;\n    SKP_int   sf_length, sf_length_8kHz;\n    SKP_int   min_lag, min_lag_8kHz, min_lag_4kHz;\n    SKP_int   max_lag, max_lag_8kHz, max_lag_4kHz;\n    SKP_int32 contour_bias, diff;\n    SKP_int32 lz, lshift;\n    SKP_int   cbk_offset, cbk_size, nb_cbks_stage2;\n    SKP_int32 delta_lag_log2_sqr_Q7, lag_log2_Q7, prevLag_log2_Q7, prev_lag_bias_Q15, corr_thres_Q15;\n\n    /* Check for valid sampling frequency */\n    SKP_assert( Fs_kHz == 8 || Fs_kHz == 12 || Fs_kHz == 16 || Fs_kHz == 24 );\n\n    /* Check for valid complexity setting */\n    SKP_assert( complexity >= SKP_Silk_PITCH_EST_MIN_COMPLEX );\n    SKP_assert( complexity <= SKP_Silk_PITCH_EST_MAX_COMPLEX );\n\n    SKP_assert( search_thres1_Q16 >= 0 && search_thres1_Q16 <= (1<<16) );\n    SKP_assert( search_thres2_Q15 >= 0 && search_thres2_Q15 <= (1<<15) );\n\n    /* Setup frame lengths max / min lag for the sampling frequency */\n    frame_length      = PITCH_EST_FRAME_LENGTH_MS * Fs_kHz;\n    frame_length_4kHz = PITCH_EST_FRAME_LENGTH_MS * 4;\n    frame_length_8kHz = PITCH_EST_FRAME_LENGTH_MS * 8;\n    sf_length         = SKP_RSHIFT( frame_length,      3 );\n    sf_length_8kHz    = SKP_RSHIFT( frame_length_8kHz, 3 );\n    min_lag           = PITCH_EST_MIN_LAG_MS * Fs_kHz;\n    min_lag_4kHz      = PITCH_EST_MIN_LAG_MS * 4;\n    min_lag_8kHz      = PITCH_EST_MIN_LAG_MS * 8;\n    max_lag           = PITCH_EST_MAX_LAG_MS * Fs_kHz;\n    max_lag_4kHz      = PITCH_EST_MAX_LAG_MS * 4;\n    max_lag_8kHz      = PITCH_EST_MAX_LAG_MS * 8;\n\n    SKP_memset( C, 0, sizeof( SKP_int16 ) * PITCH_EST_NB_SUBFR * ( ( PITCH_EST_MAX_LAG >> 1 ) + 5) );\n    \n    /* Resample from input sampled at Fs_kHz to 8 kHz */\n    if( Fs_kHz == 16 ) {\n        SKP_memset( filt_state, 0, 2 * sizeof( SKP_int32 ) );\n        SKP_Silk_resampler_down2( filt_state, signal_8kHz, signal, frame_length );\n    } else if ( Fs_kHz == 12 ) {\n        SKP_int32 R23[ 6 ];\n        SKP_memset( R23, 0, 6 * sizeof( SKP_int32 ) );\n        SKP_Silk_resampler_down2_3( R23, signal_8kHz, signal, PITCH_EST_FRAME_LENGTH_MS * 12 );\n    } else if( Fs_kHz == 24 ) {\n        SKP_int32 filt_state_fix[ 8 ];\n        SKP_memset( filt_state_fix, 0, 8 * sizeof(SKP_int32) );\n        SKP_Silk_resampler_down3( filt_state_fix, signal_8kHz, signal, 24 * PITCH_EST_FRAME_LENGTH_MS );\n    } else {\n        SKP_assert( Fs_kHz == 8 );\n        SKP_memcpy( signal_8kHz, signal, frame_length_8kHz * sizeof(SKP_int16) );\n    }\n    /* Decimate again to 4 kHz */\n    SKP_memset( filt_state, 0, 2 * sizeof( SKP_int32 ) );/* Set state to zero */\n    SKP_Silk_resampler_down2( filt_state, signal_4kHz, signal_8kHz, frame_length_8kHz );\n\n    /* Low-pass filter */\n    for( i = frame_length_4kHz - 1; i > 0; i-- ) {\n        signal_4kHz[ i ] = SKP_ADD_SAT16( signal_4kHz[ i ], signal_4kHz[ i - 1 ] );\n    }\n\n    /*******************************************************************************\n    ** Scale 4 kHz signal down to prevent correlations measures from overflowing\n    ** find scaling as max scaling for each 8kHz(?) subframe\n    *******************************************************************************/\n    \n    /* Inner product is calculated with different lengths, so scale for the worst case */\n    max_sum_sq_length = SKP_max_32( sf_length_8kHz, SKP_RSHIFT( frame_length_4kHz, 1 ) );\n    shift = SKP_FIX_P_Ana_find_scaling( signal_4kHz, frame_length_4kHz, max_sum_sq_length );\n    if( shift > 0 ) {\n        for( i = 0; i < frame_length_4kHz; i++ ) {\n            signal_4kHz[ i ] = SKP_RSHIFT( signal_4kHz[ i ], shift );\n        }\n    }\n\n    /******************************************************************************\n    * FIRST STAGE, operating in 4 khz\n    ******************************************************************************/\n    target_ptr = &signal_4kHz[ SKP_RSHIFT( frame_length_4kHz, 1 ) ];\n    for( k = 0; k < 2; k++ ) {\n        /* Check that we are within range of the array */\n        SKP_assert( target_ptr >= signal_4kHz );\n        SKP_assert( target_ptr + sf_length_8kHz <= signal_4kHz + frame_length_4kHz );\n\n        basis_ptr = target_ptr - min_lag_4kHz;\n\n        /* Check that we are within range of the array */\n        SKP_assert( basis_ptr >= signal_4kHz );\n        SKP_assert( basis_ptr + sf_length_8kHz <= signal_4kHz + frame_length_4kHz );\n\n        normalizer = 0;\n        cross_corr = 0;\n        /* Calculate first vector products before loop */\n        cross_corr = SKP_Silk_inner_prod_aligned( target_ptr, basis_ptr, sf_length_8kHz );\n        normalizer = SKP_Silk_inner_prod_aligned( basis_ptr,  basis_ptr, sf_length_8kHz );\n        normalizer = SKP_ADD_SAT32( normalizer, SKP_SMULBB( sf_length_8kHz, 4000 ) );\n\n        temp32 = SKP_DIV32( cross_corr, SKP_Silk_SQRT_APPROX( normalizer ) + 1 );\n        C[ k ][ min_lag_4kHz ] = (SKP_int16)SKP_SAT16( temp32 );        /* Q0 */\n\n        /* From now on normalizer is computed recursively */\n        for( d = min_lag_4kHz + 1; d <= max_lag_4kHz; d++ ) {\n            basis_ptr--;\n\n            /* Check that we are within range of the array */\n            SKP_assert( basis_ptr >= signal_4kHz );\n            SKP_assert( basis_ptr + sf_length_8kHz <= signal_4kHz + frame_length_4kHz );\n\n            cross_corr = SKP_Silk_inner_prod_aligned( target_ptr, basis_ptr, sf_length_8kHz );\n\n            /* Add contribution of new sample and remove contribution from oldest sample */\n            normalizer +=\n                SKP_SMULBB( basis_ptr[ 0 ], basis_ptr[ 0 ] ) - \n                SKP_SMULBB( basis_ptr[ sf_length_8kHz ], basis_ptr[ sf_length_8kHz ] ); \n    \n            temp32 = SKP_DIV32( cross_corr, SKP_Silk_SQRT_APPROX( normalizer ) + 1 );\n            C[ k ][ d ] = (SKP_int16)SKP_SAT16( temp32 );                        /* Q0 */\n        }\n        /* Update target pointer */\n        target_ptr += sf_length_8kHz;\n    }\n\n    /* Combine two subframes into single correlation measure and apply short-lag bias */\n    for( i = max_lag_4kHz; i >= min_lag_4kHz; i-- ) {\n        sum = (SKP_int32)C[ 0 ][ i ] + (SKP_int32)C[ 1 ][ i ];                /* Q0 */\n        SKP_assert( SKP_RSHIFT( sum, 1 ) == SKP_SAT16( SKP_RSHIFT( sum, 1 ) ) );\n        sum = SKP_RSHIFT( sum, 1 );                                           /* Q-1 */\n        SKP_assert( SKP_LSHIFT( (SKP_int32)-i, 4 ) == SKP_SAT16( SKP_LSHIFT( (SKP_int32)-i, 4 ) ) );\n        sum = SKP_SMLAWB( sum, sum, SKP_LSHIFT( -i, 4 ) );                    /* Q-1 */\n        SKP_assert( sum == SKP_SAT16( sum ) );\n        C[ 0 ][ i ] = (SKP_int16)sum;                                         /* Q-1 */\n    }\n\n    /* Sort */\n    length_d_srch = 4 + 2 * complexity;\n    SKP_assert( 3 * length_d_srch <= PITCH_EST_D_SRCH_LENGTH );\n    SKP_Silk_insertion_sort_decreasing_int16( &C[ 0 ][ min_lag_4kHz ], d_srch, max_lag_4kHz - min_lag_4kHz + 1, length_d_srch );\n\n    /* Escape if correlation is very low already here */\n    target_ptr = &signal_4kHz[ SKP_RSHIFT( frame_length_4kHz, 1 ) ];\n    energy = SKP_Silk_inner_prod_aligned( target_ptr, target_ptr, SKP_RSHIFT( frame_length_4kHz, 1 ) );\n    energy = SKP_ADD_POS_SAT32( energy, 1000 );                              /* Q0 */\n    Cmax = (SKP_int)C[ 0 ][ min_lag_4kHz ];                                  /* Q-1 */\n    threshold = SKP_SMULBB( Cmax, Cmax );                                    /* Q-2 */\n    /* Compare in Q-2 domain */\n    if( SKP_RSHIFT( energy, 4 + 2 ) > threshold ) {                            \n        SKP_memset( pitch_out, 0, PITCH_EST_NB_SUBFR * sizeof( SKP_int ) );\n        *LTPCorr_Q15  = 0;\n        *lagIndex     = 0;\n        *contourIndex = 0;\n        return 1;\n    }\n\n    threshold = SKP_SMULWB( search_thres1_Q16, Cmax );\n    for( i = 0; i < length_d_srch; i++ ) {\n        /* Convert to 8 kHz indices for the sorted correlation that exceeds the threshold */\n        if( C[ 0 ][ min_lag_4kHz + i ] > threshold ) {\n            d_srch[ i ] = ( d_srch[ i ] + min_lag_4kHz ) << 1;\n        } else {\n            length_d_srch = i;\n            break;\n        }\n    }\n    SKP_assert( length_d_srch > 0 );\n\n    for( i = min_lag_8kHz - 5; i < max_lag_8kHz + 5; i++ ) {\n        d_comp[ i ] = 0;\n    }\n    for( i = 0; i < length_d_srch; i++ ) {\n        d_comp[ d_srch[ i ] ] = 1;\n    }\n\n    /* Convolution */\n    for( i = max_lag_8kHz + 3; i >= min_lag_8kHz; i-- ) {\n        d_comp[ i ] += d_comp[ i - 1 ] + d_comp[ i - 2 ];\n    }\n\n    length_d_srch = 0;\n    for( i = min_lag_8kHz; i < max_lag_8kHz + 1; i++ ) {    \n        if( d_comp[ i + 1 ] > 0 ) {\n            d_srch[ length_d_srch ] = i;\n            length_d_srch++;\n        }\n    }\n\n    /* Convolution */\n    for( i = max_lag_8kHz + 3; i >= min_lag_8kHz; i-- ) {\n        d_comp[ i ] += d_comp[ i - 1 ] + d_comp[ i - 2 ] + d_comp[ i - 3 ];\n    }\n\n    length_d_comp = 0;\n    for( i = min_lag_8kHz; i < max_lag_8kHz + 4; i++ ) {    \n        if( d_comp[ i ] > 0 ) {\n            d_comp[ length_d_comp ] = i - 2;\n            length_d_comp++;\n        }\n    }\n\n    /**********************************************************************************\n    ** SECOND STAGE, operating at 8 kHz, on lag sections with high correlation\n    *************************************************************************************/\n\n    /******************************************************************************\n    ** Scale signal down to avoid correlations measures from overflowing\n    *******************************************************************************/\n    /* find scaling as max scaling for each subframe */\n    shift = SKP_FIX_P_Ana_find_scaling( signal_8kHz, frame_length_8kHz, sf_length_8kHz );\n    if( shift > 0 ) {\n        for( i = 0; i < frame_length_8kHz; i++ ) {\n            signal_8kHz[ i ] = SKP_RSHIFT( signal_8kHz[ i ], shift );\n        }\n    }\n\n    /********************************************************************************* \n    * Find energy of each subframe projected onto its history, for a range of delays\n    *********************************************************************************/\n    SKP_memset( C, 0, PITCH_EST_NB_SUBFR * ( ( PITCH_EST_MAX_LAG >> 1 ) + 5 ) * sizeof( SKP_int16 ) );\n    \n    target_ptr = &signal_8kHz[ frame_length_4kHz ]; /* point to middle of frame */\n    for( k = 0; k < PITCH_EST_NB_SUBFR; k++ ) {\n\n        /* Check that we are within range of the array */\n        SKP_assert( target_ptr >= signal_8kHz );\n        SKP_assert( target_ptr + sf_length_8kHz <= signal_8kHz + frame_length_8kHz );\n\n        energy_target = SKP_Silk_inner_prod_aligned( target_ptr, target_ptr, sf_length_8kHz );\n        // ToDo: Calculate 1 / energy_target here and save one division inside next for loop\n        for( j = 0; j < length_d_comp; j++ ) {\n            d = d_comp[ j ];\n            basis_ptr = target_ptr - d;\n\n            /* Check that we are within range of the array */\n            SKP_assert( basis_ptr >= signal_8kHz );\n            SKP_assert( basis_ptr + sf_length_8kHz <= signal_8kHz + frame_length_8kHz );\n        \n            cross_corr   = SKP_Silk_inner_prod_aligned( target_ptr, basis_ptr, sf_length_8kHz );\n            energy_basis = SKP_Silk_inner_prod_aligned( basis_ptr,  basis_ptr, sf_length_8kHz );\n            if( cross_corr > 0 ) {\n                energy = SKP_max( energy_target, energy_basis ); /* Find max to make sure first division < 1.0 */\n                lz = SKP_Silk_CLZ32( cross_corr );\n                lshift = SKP_LIMIT_32( lz - 1, 0, 15 );\n                temp32 = SKP_DIV32( SKP_LSHIFT( cross_corr, lshift ), SKP_RSHIFT( energy, 15 - lshift ) + 1 ); /* Q15 */\n                SKP_assert( temp32 == SKP_SAT16( temp32 ) );\n                temp32 = SKP_SMULWB( cross_corr, temp32 ); /* Q(-1), cc * ( cc / max(b, t) ) */\n                temp32 = SKP_ADD_SAT32( temp32, temp32 );  /* Q(0) */\n                lz = SKP_Silk_CLZ32( temp32 );\n                lshift = SKP_LIMIT_32( lz - 1, 0, 15 );\n                energy = SKP_min( energy_target, energy_basis );\n                C[ k ][ d ] = SKP_DIV32( SKP_LSHIFT( temp32, lshift ), SKP_RSHIFT( energy, 15 - lshift ) + 1 ); // Q15\n            } else {\n                C[ k ][ d ] = 0;\n            }\n        }\n        target_ptr += sf_length_8kHz;\n    }\n\n    /* search over lag range and lags codebook */\n    /* scale factor for lag codebook, as a function of center lag */\n\n    CCmax   = SKP_int32_MIN;\n    CCmax_b = SKP_int32_MIN;\n\n    CBimax = 0; /* To avoid returning undefined lag values */\n    lag = -1;   /* To check if lag with strong enough correlation has been found */\n\n    if( prevLag > 0 ) {\n        if( Fs_kHz == 12 ) {\n            prevLag = SKP_DIV32_16( SKP_LSHIFT( prevLag, 1 ), 3 );\n        } else if( Fs_kHz == 16 ) {\n            prevLag = SKP_RSHIFT( prevLag, 1 );\n        } else if( Fs_kHz == 24 ) {\n            prevLag = SKP_DIV32_16( prevLag, 3 );\n        }\n        prevLag_log2_Q7 = SKP_Silk_lin2log( (SKP_int32)prevLag );\n    } else {\n        prevLag_log2_Q7 = 0;\n    }\n    SKP_assert( search_thres2_Q15 == SKP_SAT16( search_thres2_Q15 ) );\n    corr_thres_Q15 = SKP_RSHIFT( SKP_SMULBB( search_thres2_Q15, search_thres2_Q15 ), 13 );\n\n    /* If input is 8 khz use a larger codebook here because it is last stage */\n    if( Fs_kHz == 8 && complexity > SKP_Silk_PITCH_EST_MIN_COMPLEX ) {\n        nb_cbks_stage2 = PITCH_EST_NB_CBKS_STAGE2_EXT;    \n    } else {\n        nb_cbks_stage2 = PITCH_EST_NB_CBKS_STAGE2;\n    }\n\n    for( k = 0; k < length_d_srch; k++ ) {\n        d = d_srch[ k ];\n        for( j = 0; j < nb_cbks_stage2; j++ ) {\n            CC[ j ] = 0;\n            for( i = 0; i < PITCH_EST_NB_SUBFR; i++ ) {\n                /* Try all codebooks */\n                CC[ j ] = CC[ j ] + (SKP_int32)C[ i ][ d + SKP_Silk_CB_lags_stage2[ i ][ j ] ];\n            }\n        }\n        /* Find best codebook */\n        CCmax_new = SKP_int32_MIN;\n        CBimax_new = 0;\n        for( i = 0; i < nb_cbks_stage2; i++ ) {\n            if( CC[ i ] > CCmax_new ) {\n                CCmax_new = CC[ i ];\n                CBimax_new = i;\n            }\n        }\n\n        /* Bias towards shorter lags */\n        lag_log2_Q7 = SKP_Silk_lin2log( (SKP_int32)d ); /* Q7 */\n\t    SKP_assert( lag_log2_Q7 == SKP_SAT16( lag_log2_Q7 ) );\n\t\tSKP_assert( PITCH_EST_NB_SUBFR * PITCH_EST_SHORTLAG_BIAS_Q15 == SKP_SAT16( PITCH_EST_NB_SUBFR * PITCH_EST_SHORTLAG_BIAS_Q15 ) );\n\n\t\tif (forLJC) {\n\t\t\tCCmax_new_b = CCmax_new;\n\t\t} else {\n\t\t\tCCmax_new_b = CCmax_new - SKP_RSHIFT( SKP_SMULBB( PITCH_EST_NB_SUBFR * PITCH_EST_SHORTLAG_BIAS_Q15, lag_log2_Q7 ), 7 ); /* Q15 */\n\t\t}\n\t\t\n        /* Bias towards previous lag */\n        SKP_assert( PITCH_EST_NB_SUBFR * PITCH_EST_PREVLAG_BIAS_Q15 == SKP_SAT16( PITCH_EST_NB_SUBFR * PITCH_EST_PREVLAG_BIAS_Q15 ) );\n        if( prevLag > 0 ) {\n            delta_lag_log2_sqr_Q7 = lag_log2_Q7 - prevLag_log2_Q7;\n            SKP_assert( delta_lag_log2_sqr_Q7 == SKP_SAT16( delta_lag_log2_sqr_Q7 ) );\n            delta_lag_log2_sqr_Q7 = SKP_RSHIFT( SKP_SMULBB( delta_lag_log2_sqr_Q7, delta_lag_log2_sqr_Q7 ), 7 );\n            prev_lag_bias_Q15 = SKP_RSHIFT( SKP_SMULBB( PITCH_EST_NB_SUBFR * PITCH_EST_PREVLAG_BIAS_Q15, ( *LTPCorr_Q15 ) ), 15 ); /* Q15 */\n            prev_lag_bias_Q15 = SKP_DIV32( SKP_MUL( prev_lag_bias_Q15, delta_lag_log2_sqr_Q7 ), delta_lag_log2_sqr_Q7 + ( 1 << 6 ) );\n            CCmax_new_b -= prev_lag_bias_Q15; /* Q15 */\n        }\n\n        if ( CCmax_new_b > CCmax_b                                          &&              /* Find maximum biased correlation                  */\n              CCmax_new > corr_thres_Q15                                    &&              /* Correlation needs to be high enough to be voiced */\n             SKP_Silk_CB_lags_stage2[ 0 ][ CBimax_new ] <= min_lag_8kHz                   /* Lag must be in range                             */\n            ) {\n            CCmax_b = CCmax_new_b;\n            CCmax   = CCmax_new;\n            lag     = d;\n            CBimax  = CBimax_new;\n        }\n    }\n\n    if( lag == -1 ) {\n        /* No suitable candidate found */\n        SKP_memset( pitch_out, 0, PITCH_EST_NB_SUBFR * sizeof( SKP_int ) );\n        *LTPCorr_Q15  = 0;\n        *lagIndex     = 0;\n        *contourIndex = 0;\n        return 1;\n    }\n\n    if( Fs_kHz > 8 ) {\n\n        /******************************************************************************\n        ** Scale input signal down to avoid correlations measures from overflowing\n        *******************************************************************************/\n        /* find scaling as max scaling for each subframe */\n        shift = SKP_FIX_P_Ana_find_scaling( signal, frame_length, sf_length );\n        if( shift > 0 ) {\n            /* Move signal to scratch mem because the input signal should be unchanged */\n            /* Reuse the 32 bit scratch mem vector, use a 16 bit pointer from now */\n            input_signal_ptr = (SKP_int16*)scratch_mem;\n            for( i = 0; i < frame_length; i++ ) {\n                input_signal_ptr[ i ] = SKP_RSHIFT( signal[ i ], shift );\n            }\n        } else {\n            input_signal_ptr = (SKP_int16*)signal;\n        }\n        /*********************************************************************************/\n\n        /* Search in original signal */\n                    \n        CBimax_old = CBimax;\n        /* Compensate for decimation */\n        SKP_assert( lag == SKP_SAT16( lag ) );\n        if( Fs_kHz == 12 ) {\n            lag = SKP_RSHIFT( SKP_SMULBB( lag, 3 ), 1 );\n        } else if( Fs_kHz == 16 ) {\n            lag = SKP_LSHIFT( lag, 1 );\n        } else {\n            lag = SKP_SMULBB( lag, 3 );\n        }\n\n        lag = SKP_LIMIT_int( lag, min_lag, max_lag );\n        start_lag = SKP_max_int( lag - 2, min_lag );\n        end_lag   = SKP_min_int( lag + 2, max_lag );\n        lag_new   = lag;                                    /* to avoid undefined lag */\n        CBimax    = 0;                                        /* to avoid undefined lag */\n        SKP_assert( SKP_LSHIFT( CCmax, 13 ) >= 0 ); \n        *LTPCorr_Q15 = (SKP_int)SKP_Silk_SQRT_APPROX( SKP_LSHIFT( CCmax, 13 ) ); /* Output normalized correlation */\n\n        CCmax = SKP_int32_MIN;\n        /* pitch lags according to second stage */\n        for( k = 0; k < PITCH_EST_NB_SUBFR; k++ ) {\n            pitch_out[ k ] = lag + 2 * SKP_Silk_CB_lags_stage2[ k ][ CBimax_old ];\n        }\n        /* Calculate the correlations and energies needed in stage 3 */\n        SKP_FIX_P_Ana_calc_corr_st3(  crosscorr_st3, input_signal_ptr, start_lag, sf_length, complexity );\n        SKP_FIX_P_Ana_calc_energy_st3( energies_st3, input_signal_ptr, start_lag, sf_length, complexity );\n\n        lag_counter = 0;\n        SKP_assert( lag == SKP_SAT16( lag ) );\n        contour_bias = SKP_DIV32_16( PITCH_EST_FLATCONTOUR_BIAS_Q20, lag );\n\n        /* Setup cbk parameters acording to complexity setting */\n        cbk_size   = (SKP_int)SKP_Silk_cbk_sizes_stage3[   complexity ];\n        cbk_offset = (SKP_int)SKP_Silk_cbk_offsets_stage3[ complexity ];\n\n        for( d = start_lag; d <= end_lag; d++ ) {\n            for( j = cbk_offset; j < ( cbk_offset + cbk_size ); j++ ) {\n                cross_corr = 0;\n                energy     = 0;\n                for( k = 0; k < PITCH_EST_NB_SUBFR; k++ ) {\n                    SKP_assert( PITCH_EST_NB_SUBFR == 4 );\n                    energy     += SKP_RSHIFT( energies_st3[  k ][ j ][ lag_counter ], 2 ); /* use mean, to avoid overflow */\n                    SKP_assert( energy >= 0 );\n                    cross_corr += SKP_RSHIFT( crosscorr_st3[ k ][ j ][ lag_counter ], 2 ); /* use mean, to avoid overflow */\n                }\n                if( cross_corr > 0 ) {\n                    /* Divide cross_corr / energy and get result in Q15 */\n                    lz = SKP_Silk_CLZ32( cross_corr );\n                    /* Divide with result in Q13, cross_corr could be larger than energy */\n                    lshift = SKP_LIMIT_32( lz - 1, 0, 13 );\n                    CCmax_new = SKP_DIV32( SKP_LSHIFT( cross_corr, lshift ), SKP_RSHIFT( energy, 13 - lshift ) + 1 );\n                    CCmax_new = SKP_SAT16( CCmax_new );\n                    CCmax_new = SKP_SMULWB( cross_corr, CCmax_new );\n                    /* Saturate */\n                    if( CCmax_new > SKP_RSHIFT( SKP_int32_MAX, 3 ) ) {\n                        CCmax_new = SKP_int32_MAX;\n                    } else {\n                        CCmax_new = SKP_LSHIFT( CCmax_new, 3 );\n                    }\n                    /* Reduce depending on flatness of contour */\n                    diff = j - SKP_RSHIFT( PITCH_EST_NB_CBKS_STAGE3_MAX, 1 );\n                    diff = SKP_MUL( diff, diff );\n                    diff = SKP_int16_MAX - SKP_RSHIFT( SKP_MUL( contour_bias, diff ), 5 ); /* Q20 -> Q15 */\n                    SKP_assert( diff == SKP_SAT16( diff ) );\n                    CCmax_new = SKP_LSHIFT( SKP_SMULWB( CCmax_new, diff ), 1 );\n                } else {\n                    CCmax_new = 0;\n                }\n\n                if( CCmax_new > CCmax                                               && \n                   ( d + (SKP_int)SKP_Silk_CB_lags_stage3[ 0 ][ j ] ) <= max_lag  \n                   ) {\n                    CCmax   = CCmax_new;\n                    lag_new = d;\n                    CBimax  = j;\n                }\n            }\n            lag_counter++;\n        }\n\n        for( k = 0; k < PITCH_EST_NB_SUBFR; k++ ) {\n            pitch_out[ k ] = lag_new + SKP_Silk_CB_lags_stage3[ k ][ CBimax ];\n        }\n        *lagIndex = lag_new - min_lag;\n        *contourIndex = CBimax;\n    } else {\n        /* Save Lags and correlation */\n        CCmax = SKP_max( CCmax, 0 );\n        *LTPCorr_Q15 = (SKP_int)SKP_Silk_SQRT_APPROX( SKP_LSHIFT( CCmax, 13 ) ); /* Output normalized correlation */\n        for( k = 0; k < PITCH_EST_NB_SUBFR; k++ ) {\n            pitch_out[ k ] = lag + SKP_Silk_CB_lags_stage2[ k ][ CBimax ];\n        }\n        *lagIndex = lag - min_lag_8kHz;\n        *contourIndex = CBimax;\n    }\n    SKP_assert( *lagIndex >= 0 );\n    /* return as voiced */\n    return 0;\n}\n\n/*************************************************************************/\n/* Calculates the correlations used in stage 3 search. In order to cover */\n/* the whole lag codebook for all the searched offset lags (lag +- 2),   */\n/*************************************************************************/\nvoid SKP_FIX_P_Ana_calc_corr_st3(\n    SKP_int32        cross_corr_st3[ PITCH_EST_NB_SUBFR ][ PITCH_EST_NB_CBKS_STAGE3_MAX ][ PITCH_EST_NB_STAGE3_LAGS ],/* (O) 3 DIM correlation array */\n    const SKP_int16  signal[],                        /* I vector to correlate         */\n    SKP_int          start_lag,                       /* I lag offset to search around */\n    SKP_int          sf_length,                       /* I length of a 5 ms subframe   */\n    SKP_int          complexity                       /* I Complexity setting          */\n)\n{\n    const SKP_int16 *target_ptr, *basis_ptr;\n    SKP_int32    cross_corr;\n    SKP_int        i, j, k, lag_counter;\n    SKP_int        cbk_offset, cbk_size, delta, idx;\n    SKP_int32    scratch_mem[ SCRATCH_SIZE ];\n\n    SKP_assert( complexity >= SKP_Silk_PITCH_EST_MIN_COMPLEX );\n    SKP_assert( complexity <= SKP_Silk_PITCH_EST_MAX_COMPLEX );\n\n    cbk_offset = SKP_Silk_cbk_offsets_stage3[ complexity ];\n    cbk_size   = SKP_Silk_cbk_sizes_stage3[   complexity ];\n\n    target_ptr = &signal[ SKP_LSHIFT( sf_length, 2 ) ]; /* Pointer to middle of frame */\n    for( k = 0; k < PITCH_EST_NB_SUBFR; k++ ) {\n        lag_counter = 0;\n\n        /* Calculate the correlations for each subframe */\n        for( j = SKP_Silk_Lag_range_stage3[ complexity ][ k ][ 0 ]; j <= SKP_Silk_Lag_range_stage3[ complexity ][ k ][ 1 ]; j++ ) {\n            basis_ptr = target_ptr - ( start_lag + j );\n            cross_corr = SKP_Silk_inner_prod_aligned( (SKP_int16*)target_ptr, (SKP_int16*)basis_ptr, sf_length );\n            SKP_assert( lag_counter < SCRATCH_SIZE );\n            scratch_mem[ lag_counter ] = cross_corr;\n            lag_counter++;\n        }\n\n        delta = SKP_Silk_Lag_range_stage3[ complexity ][ k ][ 0 ];\n        for( i = cbk_offset; i < ( cbk_offset + cbk_size ); i++ ) { \n            /* Fill out the 3 dim array that stores the correlations for */\n            /* each code_book vector for each start lag */\n            idx = SKP_Silk_CB_lags_stage3[ k ][ i ] - delta;\n            for( j = 0; j < PITCH_EST_NB_STAGE3_LAGS; j++ ) {\n                SKP_assert( idx + j < SCRATCH_SIZE );\n                SKP_assert( idx + j < lag_counter );\n                cross_corr_st3[ k ][ i ][ j ] = scratch_mem[ idx + j ];\n            }\n        }\n        target_ptr += sf_length;\n    }\n}\n\n/********************************************************************/\n/* Calculate the energies for first two subframes. The energies are */\n/* calculated recursively.                                          */\n/********************************************************************/\nvoid SKP_FIX_P_Ana_calc_energy_st3(\n    SKP_int32        energies_st3[ PITCH_EST_NB_SUBFR ][ PITCH_EST_NB_CBKS_STAGE3_MAX ][ PITCH_EST_NB_STAGE3_LAGS ],/* (O) 3 DIM energy array */\n    const SKP_int16  signal[],                        /* I vector to calc energy in    */\n    SKP_int          start_lag,                       /* I lag offset to search around */\n    SKP_int          sf_length,                       /* I length of one 5 ms subframe */\n    SKP_int          complexity                       /* I Complexity setting          */\n)\n{\n    const SKP_int16 *target_ptr, *basis_ptr;\n    SKP_int32    energy;\n    SKP_int        k, i, j, lag_counter;\n    SKP_int        cbk_offset, cbk_size, delta, idx;\n    SKP_int32    scratch_mem[ SCRATCH_SIZE ];\n\n    SKP_assert( complexity >= SKP_Silk_PITCH_EST_MIN_COMPLEX );\n    SKP_assert( complexity <= SKP_Silk_PITCH_EST_MAX_COMPLEX );\n\n    cbk_offset = SKP_Silk_cbk_offsets_stage3[ complexity ];\n    cbk_size   = SKP_Silk_cbk_sizes_stage3[   complexity ];\n\n    target_ptr = &signal[ SKP_LSHIFT( sf_length, 2 ) ];\n    for( k = 0; k < PITCH_EST_NB_SUBFR; k++ ) {\n        lag_counter = 0;\n\n        /* Calculate the energy for first lag */\n        basis_ptr = target_ptr - ( start_lag + SKP_Silk_Lag_range_stage3[ complexity ][ k ][ 0 ] );\n        energy = SKP_Silk_inner_prod_aligned( basis_ptr, basis_ptr, sf_length );\n        SKP_assert( energy >= 0 );\n        scratch_mem[ lag_counter ] = energy;\n        lag_counter++;\n\n        for( i = 1; i < ( SKP_Silk_Lag_range_stage3[ complexity ][ k ][ 1 ] - SKP_Silk_Lag_range_stage3[ complexity ][ k ][ 0 ] + 1 ); i++ ) {\n            /* remove part outside new window */\n            energy -= SKP_SMULBB( basis_ptr[ sf_length - i ], basis_ptr[ sf_length - i ] );\n            SKP_assert( energy >= 0 );\n\n            /* add part that comes into window */\n            energy = SKP_ADD_SAT32( energy, SKP_SMULBB( basis_ptr[ -i ], basis_ptr[ -i ] ) );\n            SKP_assert( energy >= 0 );\n            SKP_assert( lag_counter < SCRATCH_SIZE );\n            scratch_mem[ lag_counter ] = energy;\n            lag_counter++;\n        }\n\n        delta = SKP_Silk_Lag_range_stage3[ complexity ][ k ][ 0 ];\n        for( i = cbk_offset; i < ( cbk_offset + cbk_size ); i++ ) { \n            /* Fill out the 3 dim array that stores the correlations for    */\n            /* each code_book vector for each start lag                        */\n            idx = SKP_Silk_CB_lags_stage3[ k ][ i ] - delta;\n            for( j = 0; j < PITCH_EST_NB_STAGE3_LAGS; j++ ) {\n                SKP_assert( idx + j < SCRATCH_SIZE );\n                SKP_assert( idx + j < lag_counter );\n                energies_st3[ k ][ i ][ j ] = scratch_mem[ idx + j ];\n                SKP_assert( energies_st3[ k ][ i ][ j ] >= 0.0f );\n            }\n        }\n        target_ptr += sf_length;\n    }\n}\n\nSKP_int32 SKP_FIX_P_Ana_find_scaling(\n    const SKP_int16  *signal,\n    const SKP_int    signal_length, \n    const SKP_int    sum_sqr_len\n)\n{\n    SKP_int32 nbits, x_max;\n    \n    x_max = SKP_Silk_int16_array_maxabs( signal, signal_length );\n\n    if( x_max < SKP_int16_MAX ) {\n        /* Number of bits needed for the sum of the squares */\n        nbits = 32 - SKP_Silk_CLZ32( SKP_SMULBB( x_max, x_max ) ); \n    } else {\n        /* Here we don't know if x_max should have been SKP_int16_MAX + 1, so we expect the worst case */\n        nbits = 30;\n    }\n    nbits += 17 - SKP_Silk_CLZ16( sum_sqr_len );\n\n    /* Without a guarantee of saturation, we need to keep the 31st bit free */\n    if( nbits < 31 ) {\n        return 0;\n    } else {\n        return( nbits - 30 );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_pitch_est_tables.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_typedef.h\"\n#include \"SKP_Silk_common_pitch_est_defines.h\"\n\n/********************************************************/\n/* Auto Generated File from generate_pitch_est_tables.m */\n/********************************************************/\n\nconst SKP_int16 SKP_Silk_CB_lags_stage2[PITCH_EST_NB_SUBFR][PITCH_EST_NB_CBKS_STAGE2_EXT] =\n{\n    {0, 2,-1,-1,-1, 0, 0, 1, 1, 0, 1},\n    {0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0},\n    {0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0},\n    {0,-1, 2, 1, 0, 1, 1, 0, 0,-1,-1} \n};\n\nconst SKP_int16 SKP_Silk_CB_lags_stage3[PITCH_EST_NB_SUBFR][PITCH_EST_NB_CBKS_STAGE3_MAX] =\n{\n    {-9,-7,-6,-5,-5,-4,-4,-3,-3,-2,-2,-2,-1,-1,-1, 0, 0, 0, 1, 1, 0, 1, 2, 2, 2, 3, 3, 4, 4, 5, 6, 5, 6, 8},\n    {-3,-2,-2,-2,-1,-1,-1,-1,-1, 0, 0,-1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 2, 1, 2, 2, 2, 2, 3},\n    { 3, 3, 2, 2, 2, 2, 1, 2, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,-1, 0, 0,-1,-1,-1,-1,-1,-2,-2,-2},\n    { 9, 8, 6, 5, 6, 5, 4, 4, 3, 3, 2, 2, 2, 1, 0, 1, 1, 0, 0, 0,-1,-1,-1,-2,-2,-2,-3,-3,-4,-4,-5,-5,-6,-7}\n };\n\nconst SKP_int16 SKP_Silk_Lag_range_stage3[ SKP_Silk_PITCH_EST_MAX_COMPLEX + 1 ] [ PITCH_EST_NB_SUBFR ][ 2 ] =\n{\n    /* Lags to search for low number of stage3 cbks */\n    {\n        {-2,6},\n        {-1,5},\n        {-1,5},\n        {-2,7}\n    },\n    /* Lags to search for middle number of stage3 cbks */\n    {\n        {-4,8},\n        {-1,6},\n        {-1,6},\n        {-4,9}\n    },\n    /* Lags to search for max number of stage3 cbks */\n    {\n        {-9,12},\n        {-3,7},\n        {-2,7},\n        {-7,13}\n    }\n};\n\nconst SKP_int16 SKP_Silk_cbk_sizes_stage3[SKP_Silk_PITCH_EST_MAX_COMPLEX + 1] = \n{\n    PITCH_EST_NB_CBKS_STAGE3_MIN,\n    PITCH_EST_NB_CBKS_STAGE3_MID,\n    PITCH_EST_NB_CBKS_STAGE3_MAX\n};\n\nconst SKP_int16 SKP_Silk_cbk_offsets_stage3[SKP_Silk_PITCH_EST_MAX_COMPLEX + 1] = \n{\n    ((PITCH_EST_NB_CBKS_STAGE3_MAX - PITCH_EST_NB_CBKS_STAGE3_MIN) >> 1),\n    ((PITCH_EST_NB_CBKS_STAGE3_MAX - PITCH_EST_NB_CBKS_STAGE3_MID) >> 1),\n    0\n};\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_prefilter_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n#include \"SKP_Silk_tuning_parameters.h\"\n\n/* SKP_Silk_prefilter. Prefilter for finding Quantizer input signal */\nSKP_INLINE void SKP_Silk_prefilt_FIX(\n    SKP_Silk_prefilter_state_FIX *P,                    /* I/O state                          */\n    SKP_int32   st_res_Q12[],                           /* I short term residual signal       */\n    SKP_int16   xw[],                                   /* O prefiltered signal               */\n    SKP_int32   HarmShapeFIRPacked_Q12,                 /* I Harmonic shaping coeficients     */\n    SKP_int     Tilt_Q14,                               /* I Tilt shaping coeficient          */\n    SKP_int32   LF_shp_Q14,                             /* I Low-frequancy shaping coeficients*/\n    SKP_int     lag,                                    /* I Lag for harmonic shaping         */\n    SKP_int     length                                  /* I Length of signals                */\n);\n#if EMBEDDED_ARM<6\nvoid SKP_Silk_warped_LPC_analysis_filter_FIX(\n          SKP_int32                 state[],            /* I/O  State [order + 1]                       */\n          SKP_int16                 res[],              /* O    Residual signal [length]                */\n    const SKP_int16                 coef_Q13[],         /* I    Coefficients [order]                    */\n    const SKP_int16                 input[],            /* I    Input signal [length]                   */\n    const SKP_int16                 lambda_Q16,         /* I    Warping factor                          */\n    const SKP_int                   length,             /* I    Length of input signal                  */\n    const SKP_int                   order               /* I    Filter order (even)                     */\n)\n{\n    SKP_int     n, i;\n    SKP_int32   acc_Q11, tmp1, tmp2;\n\n    /* Order must be even */\n    SKP_assert( ( order & 1 ) == 0 );\n\n    for( n = 0; n < length; n++ ) {\n        /* Output of lowpass section */  \n        tmp2 = SKP_SMLAWB( state[ 0 ], state[ 1 ], lambda_Q16 );\n        state[ 0 ] = SKP_LSHIFT( input[ n ], 14 );\n        /* Output of allpass section */\n        tmp1 = SKP_SMLAWB( state[ 1 ], state[ 2 ] - tmp2, lambda_Q16 );\n        state[ 1 ] = tmp2;\n        acc_Q11 = SKP_SMULWB( tmp2, coef_Q13[ 0 ] );\n        /* Loop over allpass sections */\n        for( i = 2; i < order; i += 2 ) {\n            /* Output of allpass section */\n            tmp2 = SKP_SMLAWB( state[ i ], state[ i + 1 ] - tmp1, lambda_Q16 );\n            state[ i ] = tmp1;\n            acc_Q11 = SKP_SMLAWB( acc_Q11, tmp1, coef_Q13[ i - 1 ] );\n            /* Output of allpass section */\n            tmp1 = SKP_SMLAWB( state[ i + 1 ], state[ i + 2 ] - tmp2, lambda_Q16 );\n            state[ i + 1 ] = tmp2;\n            acc_Q11 = SKP_SMLAWB( acc_Q11, tmp2, coef_Q13[ i ] );\n        }\n        state[ order ] = tmp1;\n        acc_Q11 = SKP_SMLAWB( acc_Q11, tmp1, coef_Q13[ order - 1 ] );\n        res[ n ] = ( SKP_int16 )SKP_SAT16( ( SKP_int32 )input[ n ] - SKP_RSHIFT_ROUND( acc_Q11, 11 ) );\n    }\n}\n#endif\n\nvoid SKP_Silk_prefilter_FIX(\n    SKP_Silk_encoder_state_FIX          *psEnc,         /* I/O  Encoder state FIX                           */\n    const SKP_Silk_encoder_control_FIX  *psEncCtrl,     /* I    Encoder control FIX                         */\n    SKP_int16                           xw[],           /* O    Weighted signal                             */\n    const SKP_int16                     x[]             /* I    Speech signal                               */\n)\n{\n    SKP_Silk_prefilter_state_FIX *P = &psEnc->sPrefilt;\n    SKP_int   j, k, lag;\n    SKP_int32 tmp_32;\n    const SKP_int16 *AR1_shp_Q13;\n    const SKP_int16 *px;\n    SKP_int16 *pxw;\n    SKP_int   HarmShapeGain_Q12, Tilt_Q14;\n    SKP_int32 HarmShapeFIRPacked_Q12, LF_shp_Q14;\n    SKP_int32 x_filt_Q12[ MAX_FRAME_LENGTH / NB_SUBFR ];\n    SKP_int16 st_res[ ( MAX_FRAME_LENGTH / NB_SUBFR ) + MAX_SHAPE_LPC_ORDER ];\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n    SKP_int32 B_Q12;\n#else\n    SKP_int16 B_Q12[ 2 ];\n#endif\n\n    /* Setup pointers */\n    px  = x;\n    pxw = xw;\n    lag = P->lagPrev;\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        /* Update Variables that change per sub frame */\n        if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) {\n            lag = psEncCtrl->sCmn.pitchL[ k ];\n        }\n\n        /* Noise shape parameters */\n        HarmShapeGain_Q12 = SKP_SMULWB( psEncCtrl->HarmShapeGain_Q14[ k ], 16384 - psEncCtrl->HarmBoost_Q14[ k ] );\n        SKP_assert( HarmShapeGain_Q12 >= 0 );\n        HarmShapeFIRPacked_Q12  =                          SKP_RSHIFT( HarmShapeGain_Q12, 2 );\n        HarmShapeFIRPacked_Q12 |= SKP_LSHIFT( ( SKP_int32 )SKP_RSHIFT( HarmShapeGain_Q12, 1 ), 16 );\n        Tilt_Q14    = psEncCtrl->Tilt_Q14[   k ];\n        LF_shp_Q14  = psEncCtrl->LF_shp_Q14[ k ];\n        AR1_shp_Q13 = &psEncCtrl->AR1_Q13[   k * MAX_SHAPE_LPC_ORDER ];\n\n        /* Short term FIR filtering*/\n        SKP_Silk_warped_LPC_analysis_filter_FIX( P->sAR_shp, st_res, AR1_shp_Q13, px, \n            psEnc->sCmn.warping_Q16, psEnc->sCmn.subfr_length, psEnc->sCmn.shapingLPCOrder );\n\n        /* reduce (mainly) low frequencies during harmonic emphasis */\n#if !defined(_SYSTEM_IS_BIG_ENDIAN)\n        /* NOTE: the code below loads two int16 values in an int32, and multiplies each using the   */\n        /* SMLABB and SMLABT instructions. On a big-endian CPU the two int16 variables would be     */\n        /* loaded in reverse order and the code will give the wrong result. In that case swapping   */\n        /* the SMLABB and SMLABT instructions should solve the problem.                             */\n        B_Q12 = SKP_RSHIFT_ROUND( psEncCtrl->GainsPre_Q14[ k ], 2 );\n        tmp_32 = SKP_SMLABB( SKP_FIX_CONST( INPUT_TILT, 26 ), psEncCtrl->HarmBoost_Q14[ k ], HarmShapeGain_Q12 );   /* Q26 */\n        tmp_32 = SKP_SMLABB( tmp_32, psEncCtrl->coding_quality_Q14, SKP_FIX_CONST( HIGH_RATE_INPUT_TILT, 12 ) );    /* Q26 */\n        tmp_32 = SKP_SMULWB( tmp_32, -psEncCtrl->GainsPre_Q14[ k ] );                                               /* Q24 */\n        tmp_32 = SKP_RSHIFT_ROUND( tmp_32, 12 );                                                                    /* Q12 */\n        B_Q12 |= SKP_LSHIFT( SKP_SAT16( tmp_32 ), 16 );\n\n        x_filt_Q12[ 0 ] = SKP_SMLABT( SKP_SMULBB( st_res[ 0 ], B_Q12 ), P->sHarmHP, B_Q12 );\n        for( j = 1; j < psEnc->sCmn.subfr_length; j++ ) {\n            x_filt_Q12[ j ] = SKP_SMLABT( SKP_SMULBB( st_res[ j ], B_Q12 ), st_res[ j - 1 ], B_Q12 );\n        }\n#else\n        B_Q12[ 0 ] = SKP_RSHIFT_ROUND( psEncCtrl->GainsPre_Q14[ k ], 2 );\n        tmp_32 = SKP_SMLABB( SKP_FIX_CONST( INPUT_TILT, 26 ), psEncCtrl->HarmBoost_Q14[ k ], HarmShapeGain_Q12 );   /* Q26 */\n        tmp_32 = SKP_SMLABB( tmp_32, psEncCtrl->coding_quality_Q14, SKP_FIX_CONST( HIGH_RATE_INPUT_TILT, 12 ) );    /* Q26 */\n        tmp_32 = SKP_SMULWB( tmp_32, -psEncCtrl->GainsPre_Q14[ k ] );                                               /* Q24 */\n        tmp_32 = SKP_RSHIFT_ROUND( tmp_32, 12 );                                                                    /* Q12 */\n        B_Q12[ 1 ]= SKP_SAT16( tmp_32 );\n\n        x_filt_Q12[ 0 ] = SKP_SMLABB( SKP_SMULBB( st_res[ 0 ], B_Q12[ 0 ] ), P->sHarmHP, B_Q12[ 1 ] );\n        for( j = 1; j < psEnc->sCmn.subfr_length; j++ ) {\n            x_filt_Q12[ j ] = SKP_SMLABB( SKP_SMULBB( st_res[ j ], B_Q12[ 0 ] ), st_res[ j - 1 ], B_Q12[ 1 ] );\n        }\n#endif\n        P->sHarmHP = st_res[ psEnc->sCmn.subfr_length - 1 ];\n\n        SKP_Silk_prefilt_FIX( P, x_filt_Q12, pxw, HarmShapeFIRPacked_Q12, Tilt_Q14, \n            LF_shp_Q14, lag, psEnc->sCmn.subfr_length );\n\n        px  += psEnc->sCmn.subfr_length;\n        pxw += psEnc->sCmn.subfr_length;\n    }\n\n    P->lagPrev = psEncCtrl->sCmn.pitchL[ NB_SUBFR - 1 ];\n}\n\n/* SKP_Silk_prefilter. Prefilter for finding Quantizer input signal                           */\nSKP_INLINE void SKP_Silk_prefilt_FIX(\n    SKP_Silk_prefilter_state_FIX *P,                    /* I/O state                          */\n    SKP_int32   st_res_Q12[],                           /* I short term residual signal       */\n    SKP_int16   xw[],                                   /* O prefiltered signal               */\n    SKP_int32   HarmShapeFIRPacked_Q12,                 /* I Harmonic shaping coeficients     */\n    SKP_int     Tilt_Q14,                               /* I Tilt shaping coeficient          */\n    SKP_int32   LF_shp_Q14,                             /* I Low-frequancy shaping coeficients*/\n    SKP_int     lag,                                    /* I Lag for harmonic shaping         */\n    SKP_int     length                                  /* I Length of signals                */\n)\n{\n    SKP_int   i, idx, LTP_shp_buf_idx;\n    SKP_int32 n_LTP_Q12, n_Tilt_Q10, n_LF_Q10;\n    SKP_int32 sLF_MA_shp_Q12, sLF_AR_shp_Q12;\n    SKP_int16 *LTP_shp_buf;\n\n    /* To speed up use temp variables instead of using the struct */\n    LTP_shp_buf     = P->sLTP_shp;\n    LTP_shp_buf_idx = P->sLTP_shp_buf_idx;\n    sLF_AR_shp_Q12  = P->sLF_AR_shp_Q12;\n    sLF_MA_shp_Q12  = P->sLF_MA_shp_Q12;\n\n    for( i = 0; i < length; i++ ) {\n        if( lag > 0 ) {\n            /* unrolled loop */\n            SKP_assert( HARM_SHAPE_FIR_TAPS == 3 );\n            idx = lag + LTP_shp_buf_idx;\n            n_LTP_Q12 = SKP_SMULBB(            LTP_shp_buf[ ( idx - HARM_SHAPE_FIR_TAPS / 2 - 1) & LTP_MASK ], HarmShapeFIRPacked_Q12 );\n            n_LTP_Q12 = SKP_SMLABT( n_LTP_Q12, LTP_shp_buf[ ( idx - HARM_SHAPE_FIR_TAPS / 2    ) & LTP_MASK ], HarmShapeFIRPacked_Q12 );\n            n_LTP_Q12 = SKP_SMLABB( n_LTP_Q12, LTP_shp_buf[ ( idx - HARM_SHAPE_FIR_TAPS / 2 + 1) & LTP_MASK ], HarmShapeFIRPacked_Q12 );\n        } else {\n            n_LTP_Q12 = 0;\n        }\n\n        n_Tilt_Q10 = SKP_SMULWB( sLF_AR_shp_Q12, Tilt_Q14 );\n        n_LF_Q10   = SKP_SMLAWB( SKP_SMULWT( sLF_AR_shp_Q12, LF_shp_Q14 ), sLF_MA_shp_Q12, LF_shp_Q14 );\n\n        sLF_AR_shp_Q12 = SKP_SUB32( st_res_Q12[ i ], SKP_LSHIFT( n_Tilt_Q10, 2 ) );\n        sLF_MA_shp_Q12 = SKP_SUB32( sLF_AR_shp_Q12,  SKP_LSHIFT( n_LF_Q10,   2 ) );\n\n        LTP_shp_buf_idx = ( LTP_shp_buf_idx - 1 ) & LTP_MASK;\n        LTP_shp_buf[ LTP_shp_buf_idx ] = ( SKP_int16 )SKP_SAT16( SKP_RSHIFT_ROUND( sLF_MA_shp_Q12, 12 ) );\n\n        xw[i] = ( SKP_int16 )SKP_SAT16( SKP_RSHIFT_ROUND( SKP_SUB32( sLF_MA_shp_Q12, n_LTP_Q12 ), 12 ) );\n    }\n\n    /* Copy temp variable back to state */\n    P->sLF_AR_shp_Q12   = sLF_AR_shp_Q12;\n    P->sLF_MA_shp_Q12   = sLF_MA_shp_Q12;\n    P->sLTP_shp_buf_idx = LTP_shp_buf_idx;\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_process_NLSFs_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\n/* Limit, stabilize, convert and quantize NLSFs.    */ \nvoid SKP_Silk_process_NLSFs_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,             /* I/O  Encoder state FIX                           */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl,         /* I/O  Encoder control FIX                         */\n    SKP_int                         *pNLSF_Q15          /* I/O  Normalized LSFs (quant out) (0 - (2^15-1))  */\n)\n{\n    SKP_int     doInterpolate;\n    SKP_int     pNLSFW_Q6[ MAX_LPC_ORDER ];\n    SKP_int     NLSF_mu_Q15, NLSF_mu_fluc_red_Q16;\n    SKP_int32   i_sqr_Q15;\n    const SKP_Silk_NLSF_CB_struct *psNLSF_CB;\n\n    /* Used only for NLSF interpolation */\n    SKP_int     pNLSF0_temp_Q15[ MAX_LPC_ORDER ];\n    SKP_int     pNLSFW0_temp_Q6[ MAX_LPC_ORDER ];\n    SKP_int     i;\n\n    SKP_assert( psEnc->speech_activity_Q8 >=   0 );\n    SKP_assert( psEnc->speech_activity_Q8 <= 256 );\n    SKP_assert( psEncCtrl->sparseness_Q8  >=   0 );\n    SKP_assert( psEncCtrl->sparseness_Q8  <= 256 );\n    SKP_assert( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED || psEncCtrl->sCmn.sigtype == SIG_TYPE_UNVOICED );\n\n    /***********************/\n    /* Calculate mu values */\n    /***********************/\n    if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) {\n        /* NLSF_mu           = 0.002f - 0.001f * psEnc->speech_activity; */\n        /* NLSF_mu_fluc_red  = 0.1f   - 0.05f  * psEnc->speech_activity; */\n        NLSF_mu_Q15          = SKP_SMLAWB(   66,   -8388, psEnc->speech_activity_Q8 );\n        NLSF_mu_fluc_red_Q16 = SKP_SMLAWB( 6554, -838848, psEnc->speech_activity_Q8 );\n    } else { \n        /* NLSF_mu           = 0.005f - 0.004f * psEnc->speech_activity; */\n        /* NLSF_mu_fluc_red  = 0.2f   - 0.1f   * psEnc->speech_activity - 0.1f * psEncCtrl->sparseness; */\n        NLSF_mu_Q15          = SKP_SMLAWB(   164,   -33554, psEnc->speech_activity_Q8 );\n        NLSF_mu_fluc_red_Q16 = SKP_SMLAWB( 13107, -1677696, psEnc->speech_activity_Q8 + psEncCtrl->sparseness_Q8 ); \n    }\n    SKP_assert( NLSF_mu_Q15          >= 0     );\n    SKP_assert( NLSF_mu_Q15          <= 164   );\n    SKP_assert( NLSF_mu_fluc_red_Q16 >= 0     );\n    SKP_assert( NLSF_mu_fluc_red_Q16 <= 13107 );\n\n    NLSF_mu_Q15 = SKP_max( NLSF_mu_Q15, 1 );\n\n    /* Calculate NLSF weights */\n    TIC(NLSF_weights_FIX)\n    SKP_Silk_NLSF_VQ_weights_laroia( pNLSFW_Q6, pNLSF_Q15, psEnc->sCmn.predictLPCOrder );\n    TOC(NLSF_weights_FIX)\n\n    /* Update NLSF weights for interpolated NLSFs */\n    doInterpolate = ( psEnc->sCmn.useInterpolatedNLSFs == 1 ) && ( psEncCtrl->sCmn.NLSFInterpCoef_Q2 < ( 1 << 2 ) );\n    if( doInterpolate ) {\n\n        /* Calculate the interpolated NLSF vector for the first half */\n        SKP_Silk_interpolate( pNLSF0_temp_Q15, psEnc->sPred.prev_NLSFq_Q15, pNLSF_Q15, \n            psEncCtrl->sCmn.NLSFInterpCoef_Q2, psEnc->sCmn.predictLPCOrder );\n\n        /* Calculate first half NLSF weights for the interpolated NLSFs */\n        TIC(NLSF_weights_FIX)\n        SKP_Silk_NLSF_VQ_weights_laroia( pNLSFW0_temp_Q6, pNLSF0_temp_Q15, psEnc->sCmn.predictLPCOrder );\n        TOC(NLSF_weights_FIX)\n\n        /* Update NLSF weights with contribution from first half */\n        i_sqr_Q15 = SKP_LSHIFT( SKP_SMULBB( psEncCtrl->sCmn.NLSFInterpCoef_Q2, psEncCtrl->sCmn.NLSFInterpCoef_Q2 ), 11 );\n        for( i = 0; i < psEnc->sCmn.predictLPCOrder; i++ ) {\n            pNLSFW_Q6[ i ] = SKP_SMLAWB( SKP_RSHIFT( pNLSFW_Q6[ i ], 1 ), pNLSFW0_temp_Q6[ i ], i_sqr_Q15 );\n            SKP_assert( pNLSFW_Q6[ i ] <= SKP_int16_MAX );\n            SKP_assert( pNLSFW_Q6[ i ] >= 1 );\n        }\n    }\n\n    /* Set pointer to the NLSF codebook for the current signal type and LPC order */\n    psNLSF_CB = psEnc->sCmn.psNLSF_CB[ psEncCtrl->sCmn.sigtype ];\n\n    /* Quantize NLSF parameters given the trained NLSF codebooks */\n    TIC(MSVQ_encode_FIX)\n    SKP_Silk_NLSF_MSVQ_encode_FIX( psEncCtrl->sCmn.NLSFIndices, pNLSF_Q15, psNLSF_CB, \n        psEnc->sPred.prev_NLSFq_Q15, pNLSFW_Q6, NLSF_mu_Q15, NLSF_mu_fluc_red_Q16, \n        psEnc->sCmn.NLSF_MSVQ_Survivors, psEnc->sCmn.predictLPCOrder, psEnc->sCmn.first_frame_after_reset );\n    TOC(MSVQ_encode_FIX)\n\n    /* Convert quantized NLSFs back to LPC coefficients */\n    SKP_Silk_NLSF2A_stable( psEncCtrl->PredCoef_Q12[ 1 ], pNLSF_Q15, psEnc->sCmn.predictLPCOrder );\n\n    if( doInterpolate ) {\n        /* Calculate the interpolated, quantized LSF vector for the first half */\n        SKP_Silk_interpolate( pNLSF0_temp_Q15, psEnc->sPred.prev_NLSFq_Q15, pNLSF_Q15, \n            psEncCtrl->sCmn.NLSFInterpCoef_Q2, psEnc->sCmn.predictLPCOrder );\n\n        /* Convert back to LPC coefficients */\n        SKP_Silk_NLSF2A_stable( psEncCtrl->PredCoef_Q12[ 0 ], pNLSF0_temp_Q15, psEnc->sCmn.predictLPCOrder );\n\n    } else {\n        /* Copy LPC coefficients for first half from second half */\n        SKP_memcpy( psEncCtrl->PredCoef_Q12[ 0 ], psEncCtrl->PredCoef_Q12[ 1 ], psEnc->sCmn.predictLPCOrder * sizeof( SKP_int16 ) );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_process_gains_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n#include \"SKP_Silk_tuning_parameters.h\"\n\n/* Processing of gains */\nvoid SKP_Silk_process_gains_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,         /* I/O  Encoder state_FIX                           */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl      /* I/O  Encoder control_FIX                         */\n)\n{\n    SKP_Silk_shape_state_FIX    *psShapeSt = &psEnc->sShape;\n    SKP_int     k;\n    SKP_int32   s_Q16, InvMaxSqrVal_Q16, gain, gain_squared, ResNrg, ResNrgPart, quant_offset_Q10;\n\n    /* Gain reduction when LTP coding gain is high */\n    if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) {\n        /*s = -0.5f * SKP_sigmoid( 0.25f * ( psEncCtrl->LTPredCodGain - 12.0f ) ); */\n        s_Q16 = -SKP_Silk_sigm_Q15( SKP_RSHIFT_ROUND( psEncCtrl->LTPredCodGain_Q7 - SKP_FIX_CONST( 12.0, 7 ), 4 ) );\n        for( k = 0; k < NB_SUBFR; k++ ) {\n            psEncCtrl->Gains_Q16[ k ] = SKP_SMLAWB( psEncCtrl->Gains_Q16[ k ], psEncCtrl->Gains_Q16[ k ], s_Q16 );\n        }\n    }\n\n    /* Limit the quantized signal */\n    InvMaxSqrVal_Q16 = SKP_DIV32_16( SKP_Silk_log2lin( \n        SKP_SMULWB( SKP_FIX_CONST( 70.0, 7 ) - psEncCtrl->current_SNR_dB_Q7, SKP_FIX_CONST( 0.33, 16 ) ) ), psEnc->sCmn.subfr_length );\n\n    for( k = 0; k < NB_SUBFR; k++ ) {\n        /* Soft limit on ratio residual energy and squared gains */\n        ResNrg     = psEncCtrl->ResNrg[ k ];\n        ResNrgPart = SKP_SMULWW( ResNrg, InvMaxSqrVal_Q16 );\n        if( psEncCtrl->ResNrgQ[ k ] > 0 ) {\n            if( psEncCtrl->ResNrgQ[ k ] < 32 ) {\n                ResNrgPart = SKP_RSHIFT_ROUND( ResNrgPart, psEncCtrl->ResNrgQ[ k ] );\n            } else {\n                ResNrgPart = 0;\n            }\n        } else if( psEncCtrl->ResNrgQ[k] != 0 ) {\n            if( ResNrgPart > SKP_RSHIFT( SKP_int32_MAX, -psEncCtrl->ResNrgQ[ k ] ) ) {\n                ResNrgPart = SKP_int32_MAX;\n            } else {\n                ResNrgPart = SKP_LSHIFT( ResNrgPart, -psEncCtrl->ResNrgQ[ k ] );\n            }\n        }\n        gain = psEncCtrl->Gains_Q16[ k ];\n        gain_squared = SKP_ADD_SAT32( ResNrgPart, SKP_SMMUL( gain, gain ) );\n        if( gain_squared < SKP_int16_MAX ) {\n            /* recalculate with higher precision */\n            gain_squared = SKP_SMLAWW( SKP_LSHIFT( ResNrgPart, 16 ), gain, gain );\n            SKP_assert( gain_squared > 0 );\n            gain = SKP_Silk_SQRT_APPROX( gain_squared );                  /* Q8   */\n            psEncCtrl->Gains_Q16[ k ] = SKP_LSHIFT_SAT32( gain, 8 );        /* Q16  */\n        } else {\n            gain = SKP_Silk_SQRT_APPROX( gain_squared );                  /* Q0   */\n            psEncCtrl->Gains_Q16[ k ] = SKP_LSHIFT_SAT32( gain, 16 );       /* Q16  */\n        }\n    }\n\n    /* Noise shaping quantization */\n    SKP_Silk_gains_quant( psEncCtrl->sCmn.GainsIndices, psEncCtrl->Gains_Q16, \n        &psShapeSt->LastGainIndex, psEnc->sCmn.nFramesInPayloadBuf );\n    /* Set quantizer offset for voiced signals. Larger offset when LTP coding gain is low or tilt is high (ie low-pass) */\n    if( psEncCtrl->sCmn.sigtype == SIG_TYPE_VOICED ) {\n        if( psEncCtrl->LTPredCodGain_Q7 + SKP_RSHIFT( psEncCtrl->input_tilt_Q15, 8 ) > SKP_FIX_CONST( 1.0, 7 ) ) {\n            psEncCtrl->sCmn.QuantOffsetType = 0;\n        } else {\n            psEncCtrl->sCmn.QuantOffsetType = 1;\n        }\n    }\n\n    /* Quantizer boundary adjustment */\n    quant_offset_Q10 = SKP_Silk_Quantization_Offsets_Q10[ psEncCtrl->sCmn.sigtype ][ psEncCtrl->sCmn.QuantOffsetType ];\n    psEncCtrl->Lambda_Q10 = SKP_FIX_CONST( LAMBDA_OFFSET, 10 )\n                          + SKP_SMULBB( SKP_FIX_CONST( LAMBDA_DELAYED_DECISIONS, 10 ), psEnc->sCmn.nStatesDelayedDecision )\n                          + SKP_SMULWB( SKP_FIX_CONST( LAMBDA_SPEECH_ACT,        18 ), psEnc->speech_activity_Q8          )\n                          + SKP_SMULWB( SKP_FIX_CONST( LAMBDA_INPUT_QUALITY,     12 ), psEncCtrl->input_quality_Q14       )\n                          + SKP_SMULWB( SKP_FIX_CONST( LAMBDA_CODING_QUALITY,    12 ), psEncCtrl->coding_quality_Q14      )\n                          + SKP_SMULWB( SKP_FIX_CONST( LAMBDA_QUANT_OFFSET,      16 ), quant_offset_Q10                   );\n\n    SKP_assert( psEncCtrl->Lambda_Q10 > 0 );\n    SKP_assert( psEncCtrl->Lambda_Q10 < SKP_FIX_CONST( 2, 10 ) );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_quant_LTP_gains_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\nvoid SKP_Silk_quant_LTP_gains_FIX(\n    SKP_int16               B_Q14[],                /* I/O  (un)quantized LTP gains     */\n    SKP_int                 cbk_index[],            /* O    Codebook Index              */\n    SKP_int                 *periodicity_index,     /* O    Periodicity Index           */\n    const SKP_int32         W_Q18[],                /* I    Error Weights in Q18        */\n    SKP_int                 mu_Q8,                  /* I    Mu value (R/D tradeoff)     */\n    SKP_int                 lowComplexity           /* I    Flag for low complexity     */\n)\n{\n    SKP_int             j, k, temp_idx[ NB_SUBFR ], cbk_size;\n    const SKP_int16     *cl_ptr;\n    const SKP_int16     *cbk_ptr_Q14;\n    const SKP_int16     *b_Q14_ptr;\n    const SKP_int32     *W_Q18_ptr;\n    SKP_int32           rate_dist_subfr, rate_dist, min_rate_dist;\n\n\n\n    /***************************************************/\n    /* iterate over different codebooks with different */\n    /* rates/distortions, and choose best */\n    /***************************************************/\n    min_rate_dist = SKP_int32_MAX;\n    for( k = 0; k < 3; k++ ) {\n        cl_ptr      = SKP_Silk_LTP_gain_BITS_Q6_ptrs[ k ];\n        cbk_ptr_Q14 = SKP_Silk_LTP_vq_ptrs_Q14[       k ];\n        cbk_size    = SKP_Silk_LTP_vq_sizes[          k ];\n\n        /* Setup pointer to first subframe */\n        W_Q18_ptr = W_Q18;\n        b_Q14_ptr = B_Q14;\n\n        rate_dist = 0;\n        for( j = 0; j < NB_SUBFR; j++ ) {\n\n            SKP_Silk_VQ_WMat_EC_FIX(\n                &temp_idx[ j ],         /* O    index of best codebook vector                           */\n                &rate_dist_subfr,       /* O    best weighted quantization error + mu * rate            */\n                b_Q14_ptr,              /* I    input vector to be quantized                            */\n                W_Q18_ptr,              /* I    weighting matrix                                        */\n                cbk_ptr_Q14,            /* I    codebook                                                */\n                cl_ptr,                 /* I    code length for each codebook vector                    */\n                mu_Q8,                  /* I    tradeoff between weighted error and rate                */\n                cbk_size                /* I    number of vectors in codebook                           */\n            );\n\n            rate_dist = SKP_ADD_POS_SAT32( rate_dist, rate_dist_subfr );\n\n            b_Q14_ptr += LTP_ORDER;\n            W_Q18_ptr += LTP_ORDER * LTP_ORDER;\n        }\n\n        /* Avoid never finding a codebook */\n        rate_dist = SKP_min( SKP_int32_MAX - 1, rate_dist );\n\n        if( rate_dist < min_rate_dist ) {\n            min_rate_dist = rate_dist;\n            SKP_memcpy( cbk_index, temp_idx, NB_SUBFR * sizeof( SKP_int ) );\n            *periodicity_index = k;\n        }\n\n        /* Break early in low-complexity mode if rate distortion is below threshold */\n        if( lowComplexity && ( rate_dist < SKP_Silk_LTP_gain_middle_avg_RD_Q14 ) ) {\n            break;\n        }\n    }\n\n    cbk_ptr_Q14 = SKP_Silk_LTP_vq_ptrs_Q14[ *periodicity_index ];\n    for( j = 0; j < NB_SUBFR; j++ ) {\n        for( k = 0; k < LTP_ORDER; k++ ) { \n            B_Q14[ j * LTP_ORDER + k ] = cbk_ptr_Q14[ SKP_MLA( k, cbk_index[ j ], LTP_ORDER ) ];\n        }\n    }\n}\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_range_coder.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n/* Range encoder for one symbol */\nvoid SKP_Silk_range_encoder(\n    SKP_Silk_range_coder_state      *psRC,              /* I/O  compressor data structure                   */\n    const SKP_int                   data,               /* I    uncompressed data                           */\n    const SKP_uint16                prob[]              /* I    cumulative density functions                */\n)\n{\n    SKP_uint32 low_Q16, high_Q16;\n    SKP_uint32 base_tmp, range_Q32;\n\n    /* Copy structure data */\n    SKP_uint32 base_Q32  = psRC->base_Q32;\n    SKP_uint32 range_Q16 = psRC->range_Q16;\n    SKP_int32  bufferIx  = psRC->bufferIx;\n    SKP_uint8  *buffer   = psRC->buffer;\n\n    if( psRC->error ) {\n        return;\n    }\n\n    /* Update interval */\n    low_Q16  = prob[ data ];\n    high_Q16 = prob[ data + 1 ];\n    base_tmp = base_Q32; /* save current base, to test for carry */\n    base_Q32 += SKP_MUL_uint( range_Q16, low_Q16 );\n    range_Q32 = SKP_MUL_uint( range_Q16, high_Q16 - low_Q16 );\n\n    /* Check for carry */\n    if( base_Q32 < base_tmp ) {\n        /* Propagate carry in buffer */\n        SKP_int bufferIx_tmp = bufferIx;\n        while( ( ++buffer[ --bufferIx_tmp ] ) == 0 );\n    }\n\n    /* Check normalization */\n    if( range_Q32 & 0xFF000000 ) {\n        /* No normalization */\n        range_Q16 = SKP_RSHIFT_uint( range_Q32, 16 );\n    } else {\n        if( range_Q32 & 0xFFFF0000 ) {\n            /* Normalization of 8 bits shift */\n            range_Q16 = SKP_RSHIFT_uint( range_Q32, 8 );\n        } else {\n            /* Normalization of 16 bits shift */\n            range_Q16 = range_Q32;\n            /* Make sure not to write beyond buffer */\n            if( bufferIx >= psRC->bufferLength ) {\n                psRC->error = RANGE_CODER_WRITE_BEYOND_BUFFER;\n                return;\n            }\n            /* Write one byte to buffer */\n            buffer[ bufferIx++ ] = (SKP_uint8)( SKP_RSHIFT_uint( base_Q32, 24 ) );\n            base_Q32 = SKP_LSHIFT_ovflw( base_Q32, 8 );\n        }\n        /* Make sure not to write beyond buffer */\n        if( bufferIx >= psRC->bufferLength ) {\n            psRC->error = RANGE_CODER_WRITE_BEYOND_BUFFER;\n            return;\n        }\n        /* Write one byte to buffer */\n        buffer[ bufferIx++ ] = (SKP_uint8)( SKP_RSHIFT_uint( base_Q32, 24 ) );\n        base_Q32 = SKP_LSHIFT_ovflw( base_Q32, 8 );\n    }\n\n    /* Copy structure data back */\n    psRC->base_Q32  = base_Q32;\n    psRC->range_Q16 = range_Q16;\n    psRC->bufferIx  = bufferIx;\n}\n\n/* Range encoder for multiple symbols */\nvoid SKP_Silk_range_encoder_multi(\n    SKP_Silk_range_coder_state      *psRC,              /* I/O  compressor data structure                   */\n    const SKP_int                   data[],             /* I    uncompressed data    [nSymbols]             */\n    const SKP_uint16 * const        prob[],             /* I    cumulative density functions                */\n    const SKP_int                   nSymbols            /* I    number of data symbols                      */\n)\n{\n    SKP_int k;\n    for( k = 0; k < nSymbols; k++ ) {\n        SKP_Silk_range_encoder( psRC, data[ k ], prob[ k ] );\n    }\n}\n\n/* Range decoder for one symbol */\nvoid SKP_Silk_range_decoder(\n    SKP_int                         data[],             /* O    uncompressed data                           */\n    SKP_Silk_range_coder_state      *psRC,              /* I/O  compressor data structure                   */\n    const SKP_uint16                prob[],             /* I    cumulative density function                 */\n    SKP_int                         probIx              /* I    initial (middle) entry of cdf               */\n)\n{\n    SKP_uint32 low_Q16, high_Q16;\n    SKP_uint32 base_tmp, range_Q32;\n\n    /* Copy structure data */\n    SKP_uint32 base_Q32  = psRC->base_Q32;\n    SKP_uint32 range_Q16 = psRC->range_Q16;\n    SKP_int32  bufferIx  = psRC->bufferIx;\n    SKP_uint8  *buffer   = &psRC->buffer[ 4 ];\n\n    if( psRC->error ) {\n        /* Set output to zero */\n        *data = 0;\n        return;\n    }\n\n    high_Q16 = prob[ probIx ];\n    base_tmp = SKP_MUL_uint( range_Q16, high_Q16 );\n    if( base_tmp > base_Q32 ) {\n        while( 1 ) {\n            low_Q16 = prob[ --probIx ];\n            base_tmp = SKP_MUL_uint( range_Q16, low_Q16 );\n            if( base_tmp <= base_Q32 ) {\n                break;\n            }\n            high_Q16 = low_Q16;\n            /* Test for out of range */\n            if( high_Q16 == 0 ) {\n                psRC->error = RANGE_CODER_CDF_OUT_OF_RANGE;\n                /* Set output to zero */\n                *data = 0;\n                return;\n            }\n        }\n    } else {\n        while( 1 ) {\n            low_Q16  = high_Q16;\n            high_Q16 = prob[ ++probIx ];\n            base_tmp = SKP_MUL_uint( range_Q16, high_Q16 );\n            if( base_tmp > base_Q32 ) {\n                probIx--;\n                break;\n            }\n            /* Test for out of range */\n            if( high_Q16 == 0xFFFF ) {\n                psRC->error = RANGE_CODER_CDF_OUT_OF_RANGE;\n                /* Set output to zero */\n                *data = 0;\n                return;\n            }\n        }\n    }\n    *data = probIx;\n    base_Q32 -= SKP_MUL_uint( range_Q16, low_Q16 );\n    range_Q32 = SKP_MUL_uint( range_Q16, high_Q16 - low_Q16 );\n\n    /* Check normalization */\n    if( range_Q32 & 0xFF000000 ) {\n        /* No normalization */\n        range_Q16 = SKP_RSHIFT_uint( range_Q32, 16 );\n    } else {\n        if( range_Q32 & 0xFFFF0000 ) {\n            /* Normalization of 8 bits shift */\n            range_Q16 = SKP_RSHIFT_uint( range_Q32, 8 );\n            /* Check for errors */\n            if( SKP_RSHIFT_uint( base_Q32, 24 ) ) {\n                psRC->error = RANGE_CODER_NORMALIZATION_FAILED;\n                /* Set output to zero */\n                *data = 0;\n                return;\n            }\n        } else {\n            /* Normalization of 16 bits shift */\n            range_Q16 = range_Q32;\n            /* Check for errors */\n            if( SKP_RSHIFT( base_Q32, 16 ) ) {\n                psRC->error = RANGE_CODER_NORMALIZATION_FAILED;\n                /* Set output to zero */\n                *data = 0;\n                return;\n            }\n            /* Update base */\n            base_Q32 = SKP_LSHIFT_uint( base_Q32, 8 );\n            /* Make sure not to read beyond buffer */\n            if( bufferIx < psRC->bufferLength ) {\n                /* Read one byte from buffer */\n                base_Q32 |= (SKP_uint32)buffer[ bufferIx++ ];\n            }\n        }\n        /* Update base */\n        base_Q32 = SKP_LSHIFT_uint( base_Q32, 8 );\n        /* Make sure not to read beyond buffer */\n        if( bufferIx < psRC->bufferLength ) {\n            /* Read one byte from buffer */\n            base_Q32 |= (SKP_uint32)buffer[ bufferIx++ ];\n        }\n    }\n\n    /* Check for zero interval length */\n    if( range_Q16 == 0 ) {\n        psRC->error = RANGE_CODER_ZERO_INTERVAL_WIDTH;\n        /* Set output to zero */\n        *data = 0;\n        return;\n    }\n\n    /* Copy structure data back */\n    psRC->base_Q32  = base_Q32;\n    psRC->range_Q16 = range_Q16;\n    psRC->bufferIx  = bufferIx;\n}\n\n/* Range decoder for multiple symbols */\nvoid SKP_Silk_range_decoder_multi(\n    SKP_int                         data[],             /* O    uncompressed data                [nSymbols] */\n    SKP_Silk_range_coder_state      *psRC,              /* I/O  compressor data structure                   */\n    const SKP_uint16 * const        prob[],             /* I    cumulative density functions                */\n    const SKP_int                   probStartIx[],      /* I    initial (middle) entries of cdfs [nSymbols] */\n    const SKP_int                   nSymbols            /* I    number of data symbols                      */\n)\n{\n    SKP_int k;\n    for( k = 0; k < nSymbols; k++ ) {\n        SKP_Silk_range_decoder( &data[ k ], psRC, prob[ k ], probStartIx[ k ] );\n    }\n}\n\n/* Initialize range encoder */\nvoid SKP_Silk_range_enc_init(\n    SKP_Silk_range_coder_state      *psRC               /* O    compressor data structure                   */\n)\n{\n    /* Initialize structure */\n    psRC->bufferLength = MAX_ARITHM_BYTES;\n    psRC->range_Q16    = 0x0000FFFF;\n    psRC->bufferIx     = 0;\n    psRC->base_Q32     = 0;\n    psRC->error        = 0;\n}\n\n/* Initialize range decoder */\nvoid SKP_Silk_range_dec_init(\n    SKP_Silk_range_coder_state      *psRC,              /* O    compressor data structure                   */\n    const SKP_uint8                 buffer[],           /* I    buffer for compressed data [bufferLength]   */\n    const SKP_int32                 bufferLength        /* I    buffer length (in bytes)                    */\n)\n{\n    /* check input */\n    if( ( bufferLength > MAX_ARITHM_BYTES ) || ( bufferLength < 0 ) ) {\n        psRC->error = RANGE_CODER_DEC_PAYLOAD_TOO_LONG;\n        return;\n    }\n    /* Initialize structure */\n    /* Copy to internal buffer */\n    SKP_memcpy( psRC->buffer, buffer, bufferLength * sizeof( SKP_uint8 ) ); \n    psRC->bufferLength = bufferLength;\n    psRC->bufferIx = 0;\n    psRC->base_Q32 = \n        SKP_LSHIFT_uint( (SKP_uint32)buffer[ 0 ], 24 ) | \n        SKP_LSHIFT_uint( (SKP_uint32)buffer[ 1 ], 16 ) | \n        SKP_LSHIFT_uint( (SKP_uint32)buffer[ 2 ],  8 ) | \n                         (SKP_uint32)buffer[ 3 ];\n    psRC->range_Q16 = 0x0000FFFF;\n    psRC->error     = 0;\n}\n\n/* Determine length of bitstream */\nSKP_int SKP_Silk_range_coder_get_length(                /* O    returns number of BITS in stream            */\n    const SKP_Silk_range_coder_state    *psRC,          /* I    compressed data structure                   */\n    SKP_int                             *nBytes         /* O    number of BYTES in stream                   */\n)\n{\n    SKP_int nBits;\n\n    /* Number of bits in stream */\n    nBits = SKP_LSHIFT( psRC->bufferIx, 3 ) + SKP_Silk_CLZ32( psRC->range_Q16 - 1 ) - 14;\n\n    *nBytes = SKP_RSHIFT( nBits + 7, 3 );\n\n    /* Return number of bits in bitstream */\n    return nBits;\n}\n\n/* Write shortest uniquely decodable stream to buffer, and determine its length */\nvoid SKP_Silk_range_enc_wrap_up(\n    SKP_Silk_range_coder_state      *psRC               /* I/O  compressed data structure                   */\n)\n{\n    SKP_int bufferIx_tmp, bits_to_store, bits_in_stream, nBytes, mask;\n    SKP_uint32 base_Q24;\n\n    /* Lower limit of interval, shifted 8 bits to the right */\n    base_Q24 = SKP_RSHIFT_uint( psRC->base_Q32, 8 );\n\n    bits_in_stream = SKP_Silk_range_coder_get_length( psRC, &nBytes );\n\n    /* Number of additional bits (1..9) required to be stored to stream */\n    bits_to_store = bits_in_stream - SKP_LSHIFT( psRC->bufferIx, 3 );\n    /* Round up to required resolution */\n    base_Q24 += SKP_RSHIFT_uint(  0x00800000, bits_to_store - 1 );\n    base_Q24 &= SKP_LSHIFT_ovflw( 0xFFFFFFFF, 24 - bits_to_store );\n\n    /* Check for carry */\n    if( base_Q24 & 0x01000000 ) {\n        /* Propagate carry in buffer */\n        bufferIx_tmp = psRC->bufferIx;\n        while( ( ++( psRC->buffer[ --bufferIx_tmp ] ) ) == 0 );\n    }\n\n    /* Store to stream, making sure not to write beyond buffer */\n    if( psRC->bufferIx < psRC->bufferLength ) {\n        psRC->buffer[ psRC->bufferIx++ ] = (SKP_uint8)SKP_RSHIFT_uint( base_Q24, 16 );\n        if( bits_to_store > 8 ) {\n            if( psRC->bufferIx < psRC->bufferLength ) {\n                psRC->buffer[ psRC->bufferIx++ ] = (SKP_uint8)SKP_RSHIFT_uint( base_Q24, 8 );\n            }\n        }\n    }\n\n    /* Fill up any remaining bits in the last byte with 1s */\n    if( bits_in_stream & 7 ) {\n        mask = SKP_RSHIFT( 0xFF, bits_in_stream & 7 );\n        if( nBytes - 1 < psRC->bufferLength ) {\n            psRC->buffer[ nBytes - 1 ] |= mask;\n        }\n    }\n}\n\n/* Check that any remaining bits in the last byte are set to 1 */\nvoid SKP_Silk_range_coder_check_after_decoding(\n    SKP_Silk_range_coder_state      *psRC               /* I/O  compressed data structure                   */\n)\n{\n    SKP_int bits_in_stream, nBytes, mask;\n\n    bits_in_stream = SKP_Silk_range_coder_get_length( psRC, &nBytes );\n\n    /* Make sure not to read beyond buffer */\n    if( nBytes - 1 >= psRC->bufferLength ) {\n        psRC->error = RANGE_CODER_DECODER_CHECK_FAILED;\n        return;\n    }\n\n    /* Test any remaining bits in last byte */\n    if( bits_in_stream & 7 ) {\n        mask = SKP_RSHIFT( 0xFF, bits_in_stream & 7 );\n        if( ( psRC->buffer[ nBytes - 1 ] & mask ) != mask ) {\n            psRC->error = RANGE_CODER_DECODER_CHECK_FAILED;\n            return;\n        }\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_regularize_correlations_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\n/* Add noise to matrix diagonal */\nvoid SKP_Silk_regularize_correlations_FIX(\n    SKP_int32                       *XX,                /* I/O  Correlation matrices                        */\n    SKP_int32                       *xx,                /* I/O  Correlation values                          */\n    SKP_int32                       noise,              /* I    Noise to add                                */\n    SKP_int                         D                   /* I    Dimension of XX                             */\n)\n{\n    SKP_int i;\n    for( i = 0; i < D; i++ ) {\n        matrix_ptr( &XX[ 0 ], i, i, D ) = SKP_ADD32( matrix_ptr( &XX[ 0 ], i, i, D ), noise );\n    }\n    xx[ 0 ] += noise;\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * File Name:\tSKP_Silk_resampler.c\t\t\t\t\t\t\t\t\t*\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * Description: Interface to collection of resamplers\t\t\t\t\t*\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n * All rights reserved.\t\t\t\t\t\t\t\t\t\t\t\t\t*\n *                                                                      */\n\n/* Matrix of resampling methods used:\n *                                        Fs_out (kHz)\n *                        8      12     16     24     32     44.1   48\n *\n *               8        C      UF     U      UF     UF     UF     UF\n *              12        AF     C      UF     U      UF     UF     UF\n *              16        D      AF     C      UF     U      UF     UF\n * Fs_in (kHz)  24        AIF    D      AF     C      UF     UF     U\n *              32        UF     AF     D      AF     C      UF     UF\n *              44.1      AMI    AMI    AMI    AMI    AMI    C      UF\n *              48        DAF    DAF    AF     D      AF     UF     C\n *\n * default method: UF\n *\n * C   -> Copy (no resampling)\n * D   -> Allpass-based 2x downsampling\n * U   -> Allpass-based 2x upsampling\n * DAF -> Allpass-based 2x downsampling followed by AR2 filter followed by FIR interpolation\n * UF  -> Allpass-based 2x upsampling followed by FIR interpolation\n * AMI -> ARMA4 filter followed by FIR interpolation\n * AF  -> AR2 filter followed by FIR interpolation\n *\n * Input signals sampled above 48 kHz are first downsampled to at most 48 kHz.\n * Output signals sampled above 48 kHz are upsampled from at most 48 kHz.\n */\n\n#include \"SKP_Silk_resampler_private.h\"\n\n/* Greatest common divisor */\nstatic SKP_int32 gcd(\n    SKP_int32 a,\n    SKP_int32 b\n)\n{\n    SKP_int32 tmp;\n    while( b > 0 ) {\n        tmp = a - b * SKP_DIV32( a, b );\n        a   = b;\n        b   = tmp;\n    }\n    return a;\n}\n\n/* Initialize/reset the resampler state for a given pair of input/output sampling rates */\nSKP_int SKP_Silk_resampler_init( \n\tSKP_Silk_resampler_state_struct\t*S,\t\t    /* I/O: Resampler state \t\t\t*/\n\tSKP_int32\t\t\t\t\t\t\tFs_Hz_in,\t/* I:\tInput sampling rate (Hz)\t*/\n\tSKP_int32\t\t\t\t\t\t\tFs_Hz_out\t/* I:\tOutput sampling rate (Hz)\t*/\n)\n{\n    SKP_int32 cycleLen, cyclesPerBatch, up2 = 0, down2 = 0;\n\n\t/* Clear state */\n\tSKP_memset( S, 0, sizeof( SKP_Silk_resampler_state_struct ) );\n\n\t/* Input checking */\n#if RESAMPLER_SUPPORT_ABOVE_48KHZ\n\tif( Fs_Hz_in < 8000 || Fs_Hz_in > 192000 || Fs_Hz_out < 8000 || Fs_Hz_out > 192000 ) {\n#else\n    if( Fs_Hz_in < 8000 || Fs_Hz_in >  48000 || Fs_Hz_out < 8000 || Fs_Hz_out >  48000 ) {\n#endif\n\t\tSKP_assert( 0 );\n\t\treturn -1;\n\t}\n\n#if RESAMPLER_SUPPORT_ABOVE_48KHZ\n\t/* Determine pre downsampling and post upsampling */\n\tif( Fs_Hz_in > 96000 ) {\n\t\tS->nPreDownsamplers = 2;\n        S->down_pre_function = SKP_Silk_resampler_private_down4;\n    } else if( Fs_Hz_in > 48000 ) {\n\t\tS->nPreDownsamplers = 1;\n        S->down_pre_function = SKP_Silk_resampler_down2;\n    } else {\n\t\tS->nPreDownsamplers = 0;\n        S->down_pre_function = NULL;\n    }\n\n\tif( Fs_Hz_out > 96000 ) {\n\t\tS->nPostUpsamplers = 2;\n        S->up_post_function = SKP_Silk_resampler_private_up4;\n    } else if( Fs_Hz_out > 48000 ) {\n\t\tS->nPostUpsamplers = 1;\n        S->up_post_function = SKP_Silk_resampler_up2;\n    } else {\n\t\tS->nPostUpsamplers = 0;\n        S->up_post_function = NULL;\n    }\n\n    if( S->nPreDownsamplers + S->nPostUpsamplers > 0 ) {\n        /* Ratio of output/input samples */\n\t    S->ratio_Q16 = SKP_LSHIFT32( SKP_DIV32( SKP_LSHIFT32( Fs_Hz_out, 13 ), Fs_Hz_in ), 3 );\n        /* Make sure the ratio is rounded up */\n        while( SKP_SMULWW( S->ratio_Q16, Fs_Hz_in ) < Fs_Hz_out ) S->ratio_Q16++;\n\n        /* Batch size is 10 ms */\n        S->batchSizePrePost = SKP_DIV32_16( Fs_Hz_in, 100 );\n\n        /* Convert sampling rate to those after pre-downsampling and before post-upsampling */\n\t    Fs_Hz_in  = SKP_RSHIFT( Fs_Hz_in,  S->nPreDownsamplers  );\n\t    Fs_Hz_out = SKP_RSHIFT( Fs_Hz_out, S->nPostUpsamplers  );\n    }\n#endif\n\n    /* Number of samples processed per batch */\n    /* First, try 10 ms frames */\n    S->batchSize = SKP_DIV32_16( Fs_Hz_in, 100 );\n    if( ( SKP_MUL( S->batchSize, 100 ) != Fs_Hz_in ) || ( Fs_Hz_in % 100 != 0 ) ) {\n        /* No integer number of input or output samples with 10 ms frames, use greatest common divisor */\n        cycleLen = SKP_DIV32( Fs_Hz_in, gcd( Fs_Hz_in, Fs_Hz_out ) );\n        cyclesPerBatch = SKP_DIV32( RESAMPLER_MAX_BATCH_SIZE_IN, cycleLen );\n        if( cyclesPerBatch == 0 ) {\n            /* cycleLen too big, let's just use the maximum batch size. Some distortion will result. */\n            S->batchSize = RESAMPLER_MAX_BATCH_SIZE_IN;\n            SKP_assert( 0 );\n        } else {\n            S->batchSize = SKP_MUL( cyclesPerBatch, cycleLen );\n        }\n    }\n\n\n\t/* Find resampler with the right sampling ratio */\n    if( Fs_Hz_out > Fs_Hz_in ) {\n        /* Upsample */\n        if( Fs_Hz_out == SKP_MUL( Fs_Hz_in, 2 ) ) {                             /* Fs_out : Fs_in = 2 : 1 */\n            /* Special case: directly use 2x upsampler */\n    \t    S->resampler_function = SKP_Silk_resampler_private_up2_HQ_wrapper;\n        } else {\n\t        /* Default resampler */\n\t        S->resampler_function = SKP_Silk_resampler_private_IIR_FIR;\n            up2 = 1;\n            if( Fs_Hz_in > 24000 ) {\n                /* Low-quality all-pass upsampler */\n                S->up2_function = SKP_Silk_resampler_up2;\n            } else {\n                /* High-quality all-pass upsampler */\n                S->up2_function = SKP_Silk_resampler_private_up2_HQ;\n            }\n        }\n    } else if ( Fs_Hz_out < Fs_Hz_in ) {\n        /* Downsample */\n        if( SKP_MUL( Fs_Hz_out, 4 ) == SKP_MUL( Fs_Hz_in, 3 ) ) {               /* Fs_out : Fs_in = 3 : 4 */\n    \t    S->FIR_Fracs = 3;\n    \t    S->Coefs = SKP_Silk_Resampler_3_4_COEFS;\n    \t    S->resampler_function = SKP_Silk_resampler_private_down_FIR;\n        } else if( SKP_MUL( Fs_Hz_out, 3 ) == SKP_MUL( Fs_Hz_in, 2 ) ) {        /* Fs_out : Fs_in = 2 : 3 */\n    \t    S->FIR_Fracs = 2;\n    \t    S->Coefs = SKP_Silk_Resampler_2_3_COEFS;\n    \t    S->resampler_function = SKP_Silk_resampler_private_down_FIR;\n        } else if( SKP_MUL( Fs_Hz_out, 2 ) == Fs_Hz_in ) {                      /* Fs_out : Fs_in = 1 : 2 */\n    \t    S->FIR_Fracs = 1;\n    \t    S->Coefs = SKP_Silk_Resampler_1_2_COEFS;\n    \t    S->resampler_function = SKP_Silk_resampler_private_down_FIR;\n        } else if( SKP_MUL( Fs_Hz_out, 8 ) == SKP_MUL( Fs_Hz_in, 3 ) ) {        /* Fs_out : Fs_in = 3 : 8 */\n    \t    S->FIR_Fracs = 3;\n    \t    S->Coefs = SKP_Silk_Resampler_3_8_COEFS;\n    \t    S->resampler_function = SKP_Silk_resampler_private_down_FIR;\n        } else if( SKP_MUL( Fs_Hz_out, 3 ) == Fs_Hz_in ) {                      /* Fs_out : Fs_in = 1 : 3 */\n    \t    S->FIR_Fracs = 1;\n    \t    S->Coefs = SKP_Silk_Resampler_1_3_COEFS;\n    \t    S->resampler_function = SKP_Silk_resampler_private_down_FIR;\n        } else if( SKP_MUL( Fs_Hz_out, 4 ) == Fs_Hz_in ) {                      /* Fs_out : Fs_in = 1 : 4 */\n    \t    S->FIR_Fracs = 1;\n            down2 = 1;\n    \t    S->Coefs = SKP_Silk_Resampler_1_2_COEFS;\n            S->resampler_function = SKP_Silk_resampler_private_down_FIR;\n        } else if( SKP_MUL( Fs_Hz_out, 6 ) == Fs_Hz_in ) {                      /* Fs_out : Fs_in = 1 : 6 */\n    \t    S->FIR_Fracs = 1;\n            down2 = 1;\n    \t    S->Coefs = SKP_Silk_Resampler_1_3_COEFS;\n            S->resampler_function = SKP_Silk_resampler_private_down_FIR;\n        } else if( SKP_MUL( Fs_Hz_out, 441 ) == SKP_MUL( Fs_Hz_in, 80 ) ) {     /* Fs_out : Fs_in = 80 : 441 */\n    \t    S->Coefs = SKP_Silk_Resampler_80_441_ARMA4_COEFS;\n    \t    S->resampler_function = SKP_Silk_resampler_private_IIR_FIR;\n        } else if( SKP_MUL( Fs_Hz_out, 441 ) == SKP_MUL( Fs_Hz_in, 120 ) ) {    /* Fs_out : Fs_in = 120 : 441 */\n    \t    S->Coefs = SKP_Silk_Resampler_120_441_ARMA4_COEFS;\n    \t    S->resampler_function = SKP_Silk_resampler_private_IIR_FIR;\n        } else if( SKP_MUL( Fs_Hz_out, 441 ) == SKP_MUL( Fs_Hz_in, 160 ) ) {    /* Fs_out : Fs_in = 160 : 441 */\n    \t    S->Coefs = SKP_Silk_Resampler_160_441_ARMA4_COEFS;\n    \t    S->resampler_function = SKP_Silk_resampler_private_IIR_FIR;\n        } else if( SKP_MUL( Fs_Hz_out, 441 ) == SKP_MUL( Fs_Hz_in, 240 ) ) {    /* Fs_out : Fs_in = 240 : 441 */\n    \t    S->Coefs = SKP_Silk_Resampler_240_441_ARMA4_COEFS;\n    \t    S->resampler_function = SKP_Silk_resampler_private_IIR_FIR;\n        } else if( SKP_MUL( Fs_Hz_out, 441 ) == SKP_MUL( Fs_Hz_in, 320 ) ) {    /* Fs_out : Fs_in = 320 : 441 */\n    \t    S->Coefs = SKP_Silk_Resampler_320_441_ARMA4_COEFS;\n    \t    S->resampler_function = SKP_Silk_resampler_private_IIR_FIR;\n        } else {\n\t        /* Default resampler */\n\t        S->resampler_function = SKP_Silk_resampler_private_IIR_FIR;\n            up2 = 1;\n            if( Fs_Hz_in > 24000 ) {\n                /* Low-quality all-pass upsampler */\n                S->up2_function = SKP_Silk_resampler_up2;\n            } else {\n                /* High-quality all-pass upsampler */\n                S->up2_function = SKP_Silk_resampler_private_up2_HQ;\n            }\n        }\n    } else {\n        /* Input and output sampling rates are equal: copy */\n        S->resampler_function = SKP_Silk_resampler_private_copy;\n    }\n\n    S->input2x = up2 | down2;\n\n    /* Ratio of input/output samples */\n    S->invRatio_Q16 = SKP_LSHIFT32( SKP_DIV32( SKP_LSHIFT32( Fs_Hz_in, 14 + up2 - down2 ), Fs_Hz_out ), 2 );\n    /* Make sure the ratio is rounded up */\n    while( SKP_SMULWW( S->invRatio_Q16, SKP_LSHIFT32( Fs_Hz_out, down2 ) ) < SKP_LSHIFT32( Fs_Hz_in, up2 ) ) {\n        S->invRatio_Q16++;\n    }\n\n\tS->magic_number = 123456789;\n\n\treturn 0;\n}\n\n/* Clear the states of all resampling filters, without resetting sampling rate ratio */\nSKP_int SKP_Silk_resampler_clear( \n\tSKP_Silk_resampler_state_struct\t*S\t\t    /* I/O: Resampler state \t\t\t*/\n)\n{\n\t/* Clear state */\n\tSKP_memset( S->sDown2, 0, sizeof( S->sDown2 ) );\n\tSKP_memset( S->sIIR,   0, sizeof( S->sIIR ) );\n\tSKP_memset( S->sFIR,   0, sizeof( S->sFIR ) );\n#if RESAMPLER_SUPPORT_ABOVE_48KHZ\n\tSKP_memset( S->sDownPre, 0, sizeof( S->sDownPre ) );\n\tSKP_memset( S->sUpPost,  0, sizeof( S->sUpPost ) );\n#endif\n    return 0;\n}\n\n/* Resampler: convert from one sampling rate to another                                 */\nSKP_int SKP_Silk_resampler( \n\tSKP_Silk_resampler_state_struct\t*S,\t\t    /* I/O: Resampler state \t\t\t*/\n\tSKP_int16\t\t\t\t\t\t\tout[],\t    /* O:\tOutput signal \t\t\t\t*/\n\tconst SKP_int16\t\t\t\t\t\tin[],\t    /* I:\tInput signal\t\t\t\t*/\n\tSKP_int32\t\t\t\t\t\t\tinLen\t    /* I:\tNumber of input samples\t\t*/\n)\n{\n\t/* Verify that state was initialized and has not been corrupted */\n    if( S->magic_number != 123456789 ) {\n        SKP_assert( 0 );\n        return -1;\n    }\n\n#if RESAMPLER_SUPPORT_ABOVE_48KHZ\n\tif( S->nPreDownsamplers + S->nPostUpsamplers > 0 ) {\n\t\t/* The input and/or output sampling rate is above 48000 Hz */\n        SKP_int32       nSamplesIn, nSamplesOut;\n\t\tSKP_int16\t\tin_buf[ 480 ], out_buf[ 480 ];\n\n        while( inLen > 0 ) {\n            /* Number of input and output samples to process */\n    \t\tnSamplesIn = SKP_min( inLen, S->batchSizePrePost );\n            nSamplesOut = SKP_SMULWB( S->ratio_Q16, nSamplesIn );\n\n            SKP_assert( SKP_RSHIFT32( nSamplesIn,  S->nPreDownsamplers ) <= 480 );\n            SKP_assert( SKP_RSHIFT32( nSamplesOut, S->nPostUpsamplers  ) <= 480 );\n\n    \t\tif( S->nPreDownsamplers > 0 ) {\n                S->down_pre_function( S->sDownPre, in_buf, in, nSamplesIn );\n    \t\t    if( S->nPostUpsamplers > 0 ) {\n            \t\tS->resampler_function( S, out_buf, in_buf, SKP_RSHIFT32( nSamplesIn, S->nPreDownsamplers ) );\n                    S->up_post_function( S->sUpPost, out, out_buf, SKP_RSHIFT32( nSamplesOut, S->nPostUpsamplers ) );\n                } else {\n            \t\tS->resampler_function( S, out, in_buf, SKP_RSHIFT32( nSamplesIn, S->nPreDownsamplers ) );\n                }\n            } else {\n        \t\tS->resampler_function( S, out_buf, in, SKP_RSHIFT32( nSamplesIn, S->nPreDownsamplers ) );\n                S->up_post_function( S->sUpPost, out, out_buf, SKP_RSHIFT32( nSamplesOut, S->nPostUpsamplers ) );\n            }\n\n    \t\tin += nSamplesIn;\n            out += nSamplesOut;\n\t    \tinLen -= nSamplesIn;\n        }\n\t} else \n#endif\n\t{\n\t\t/* Input and output sampling rate are at most 48000 Hz */\n\t\tS->resampler_function( S, out, in, inLen );\n\t}\n\n\treturn 0;\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler_down2.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_resampler_down2.c                                         *\n *                                                                      *\n * Downsample by a factor 2, mediocre quality                           *\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n *                                                                      */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_resampler_rom.h\"\n\n#if (EMBEDDED_ARM<5) \n/* Downsample by a factor 2, mediocre quality */\nvoid SKP_Silk_resampler_down2(\n    SKP_int32                           *S,         /* I/O: State vector [ 2 ]                  */\n    SKP_int16                           *out,       /* O:   Output signal [ len ]               */\n    const SKP_int16                     *in,        /* I:   Input signal [ floor(len/2) ]       */\n    SKP_int32                           inLen       /* I:   Number of input samples             */\n)\n{\n    SKP_int32 k, len2 = SKP_RSHIFT32( inLen, 1 );\n    SKP_int32 in32, out32, Y, X;\n\n    SKP_assert( SKP_Silk_resampler_down2_0 > 0 );\n    SKP_assert( SKP_Silk_resampler_down2_1 < 0 );\n\n    /* Internal variables and state are in Q10 format */\n    for( k = 0; k < len2; k++ ) {\n        /* Convert to Q10 */\n        in32 = SKP_LSHIFT( (SKP_int32)in[ 2 * k ], 10 );\n\n        /* All-pass section for even input sample */\n        Y      = SKP_SUB32( in32, S[ 0 ] );\n        X      = SKP_SMLAWB( Y, Y, SKP_Silk_resampler_down2_1 );\n        out32  = SKP_ADD32( S[ 0 ], X );\n        S[ 0 ] = SKP_ADD32( in32, X );\n\n        /* Convert to Q10 */\n        in32 = SKP_LSHIFT( (SKP_int32)in[ 2 * k + 1 ], 10 );\n\n        /* All-pass section for odd input sample, and add to output of previous section */\n        Y      = SKP_SUB32( in32, S[ 1 ] );\n        X      = SKP_SMULWB( Y, SKP_Silk_resampler_down2_0 );\n        out32  = SKP_ADD32( out32, S[ 1 ] );\n        out32  = SKP_ADD32( out32, X );\n        S[ 1 ] = SKP_ADD32( in32, X );\n\n        /* Add, convert back to int16 and store to output */\n        out[ k ] = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( out32, 11 ) );\n    }\n}\n#endif\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler_down2_3.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_resampler_down2_3.c                                       *\n *                                                                      *\n * Downsample by a factor 2/3, low quality                              *\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n *                                                                      */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_resampler_private.h\"\n\n#define ORDER_FIR                   4\n\n/* Downsample by a factor 2/3, low quality */\nvoid SKP_Silk_resampler_down2_3(\n    SKP_int32                           *S,         /* I/O: State vector [ 6 ]                  */\n    SKP_int16                           *out,       /* O:   Output signal [ floor(2*inLen/3) ]  */\n    const SKP_int16                     *in,        /* I:   Input signal [ inLen ]              */\n    SKP_int32                           inLen       /* I:   Number of input samples             */\n)\n{\n\tSKP_int32 nSamplesIn, counter, res_Q6;\n\tSKP_int32 buf[ RESAMPLER_MAX_BATCH_SIZE_IN + ORDER_FIR ];\n\tSKP_int32 *buf_ptr;\n\n\t/* Copy buffered samples to start of buffer */\t\n\tSKP_memcpy( buf, S, ORDER_FIR * sizeof( SKP_int32 ) );\n\n\t/* Iterate over blocks of frameSizeIn input samples */\n\twhile( 1 ) {\n\t\tnSamplesIn = SKP_min( inLen, RESAMPLER_MAX_BATCH_SIZE_IN );\n\n\t    /* Second-order AR filter (output in Q8) */\n\t    SKP_Silk_resampler_private_AR2( &S[ ORDER_FIR ], &buf[ ORDER_FIR ], in, \n            SKP_Silk_Resampler_2_3_COEFS_LQ, nSamplesIn );\n\n\t\t/* Interpolate filtered signal */\n        buf_ptr = buf;\n        counter = nSamplesIn;\n        while( counter > 2 ) {\n            /* Inner product */\n\t\t    res_Q6 = SKP_SMULWB(         buf_ptr[ 0 ], SKP_Silk_Resampler_2_3_COEFS_LQ[ 2 ] );\n\t\t    res_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[ 1 ], SKP_Silk_Resampler_2_3_COEFS_LQ[ 3 ] );\n\t\t    res_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[ 2 ], SKP_Silk_Resampler_2_3_COEFS_LQ[ 5 ] );\n\t\t    res_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[ 3 ], SKP_Silk_Resampler_2_3_COEFS_LQ[ 4 ] );\n\n            /* Scale down, saturate and store in output array */\n            *out++ = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( res_Q6, 6 ) );\n\n\t\t    res_Q6 = SKP_SMULWB(         buf_ptr[ 1 ], SKP_Silk_Resampler_2_3_COEFS_LQ[ 4 ] );\n\t\t    res_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[ 2 ], SKP_Silk_Resampler_2_3_COEFS_LQ[ 5 ] );\n\t\t    res_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[ 3 ], SKP_Silk_Resampler_2_3_COEFS_LQ[ 3 ] );\n\t\t    res_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[ 4 ], SKP_Silk_Resampler_2_3_COEFS_LQ[ 2 ] );\n\n            /* Scale down, saturate and store in output array */\n            *out++ = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( res_Q6, 6 ) );\n\n            buf_ptr += 3;\n            counter -= 3;\n        }\n\n\t\tin += nSamplesIn;\n\t\tinLen -= nSamplesIn;\n\n\t\tif( inLen > 0 ) {\n\t\t\t/* More iterations to do; copy last part of filtered signal to beginning of buffer */\n\t\t\tSKP_memcpy( buf, &buf[ nSamplesIn ], ORDER_FIR * sizeof( SKP_int32 ) );\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* Copy last part of filtered signal to the state for the next call */\n\tSKP_memcpy( S, &buf[ nSamplesIn ], ORDER_FIR * sizeof( SKP_int32 ) );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler_down3.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_resampler_down3.c                                         *\n *                                                                      *\n * Downsample by a factor 3, low quality                                *\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n *                                                                      */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_resampler_private.h\"\n\n#define ORDER_FIR                   6\n\n/* Downsample by a factor 3, low quality */\nvoid SKP_Silk_resampler_down3(\n    SKP_int32                           *S,         /* I/O: State vector [ 8 ]                  */\n    SKP_int16                           *out,       /* O:   Output signal [ floor(inLen/3) ]    */\n    const SKP_int16                     *in,        /* I:   Input signal [ inLen ]              */\n    SKP_int32                           inLen       /* I:   Number of input samples             */\n)\n{\n\tSKP_int32 nSamplesIn, counter, res_Q6;\n\tSKP_int32 buf[ RESAMPLER_MAX_BATCH_SIZE_IN + ORDER_FIR ];\n\tSKP_int32 *buf_ptr;\n\n\t/* Copy buffered samples to start of buffer */\t\n\tSKP_memcpy( buf, S, ORDER_FIR * sizeof( SKP_int32 ) );\n\n\t/* Iterate over blocks of frameSizeIn input samples */\n\twhile( 1 ) {\n\t\tnSamplesIn = SKP_min( inLen, RESAMPLER_MAX_BATCH_SIZE_IN );\n\n\t    /* Second-order AR filter (output in Q8) */\n\t    SKP_Silk_resampler_private_AR2( &S[ ORDER_FIR ], &buf[ ORDER_FIR ], in, \n            SKP_Silk_Resampler_1_3_COEFS_LQ, nSamplesIn );\n\n\t\t/* Interpolate filtered signal */\n        buf_ptr = buf;\n        counter = nSamplesIn;\n        while( counter > 2 ) {\n            /* Inner product */\n            res_Q6 = SKP_SMULWB(         SKP_ADD32( buf_ptr[ 0 ], buf_ptr[ 5 ] ), SKP_Silk_Resampler_1_3_COEFS_LQ[ 2 ] );\n            res_Q6 = SKP_SMLAWB( res_Q6, SKP_ADD32( buf_ptr[ 1 ], buf_ptr[ 4 ] ), SKP_Silk_Resampler_1_3_COEFS_LQ[ 3 ] );\n            res_Q6 = SKP_SMLAWB( res_Q6, SKP_ADD32( buf_ptr[ 2 ], buf_ptr[ 3 ] ), SKP_Silk_Resampler_1_3_COEFS_LQ[ 4 ] );\n\n            /* Scale down, saturate and store in output array */\n            *out++ = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( res_Q6, 6 ) );\n\n            buf_ptr += 3;\n            counter -= 3;\n        }\n\n\t\tin += nSamplesIn;\n\t\tinLen -= nSamplesIn;\n\n\t\tif( inLen > 0 ) {\n\t\t\t/* More iterations to do; copy last part of filtered signal to beginning of buffer */\n\t\t\tSKP_memcpy( buf, &buf[ nSamplesIn ], ORDER_FIR * sizeof( SKP_int32 ) );\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* Copy last part of filtered signal to the state for the next call */\n\tSKP_memcpy( S, &buf[ nSamplesIn ], ORDER_FIR * sizeof( SKP_int32 ) );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler_private_AR2.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * SKP_Silk_resampler_private_AR2. c                                  *\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * Second order AR filter with single delay elements                \t*\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n *                                                                      */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_resampler_private.h\"\n\n#if (EMBEDDED_ARM<5)  \n/* Second order AR filter with single delay elements */\nvoid SKP_Silk_resampler_private_AR2(\n\tSKP_int32\t\t\t\t\t    S[],\t\t    /* I/O: State vector [ 2 ]\t\t\t    \t    */\n\tSKP_int32\t\t\t\t\t    out_Q8[],\t\t/* O:\tOutput signal\t\t\t\t    \t    */\n\tconst SKP_int16\t\t\t\t    in[],\t\t\t/* I:\tInput signal\t\t\t\t    \t    */\n\tconst SKP_int16\t\t\t\t    A_Q14[],\t\t/* I:\tAR coefficients, Q14 \t                */\n\tSKP_int32\t\t\t\t        len\t\t\t\t/* I:\tSignal length\t\t\t\t        \t*/\n)\n{\n\tSKP_int32\tk;\n\tSKP_int32\tout32;\n\n\tfor( k = 0; k < len; k++ ) {\n\t\tout32       = SKP_ADD_LSHIFT32( S[ 0 ], (SKP_int32)in[ k ], 8 );\n\t\tout_Q8[ k ] = out32;\n\t\tout32       = SKP_LSHIFT( out32, 2 );\n\t\tS[ 0 ]      = SKP_SMLAWB( S[ 1 ], out32, A_Q14[ 0 ] );\n\t\tS[ 1 ]      = SKP_SMULWB( out32, A_Q14[ 1 ] );\n\t}\n}\n#endif\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler_private_ARMA4.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * SKP_Silk_resampler_private_ARMA4.c                                 *\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * Fourth order ARMA filter, applies 64x gain                           *\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n *                                                                      */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_resampler_private.h\"\n\n/* Fourth order ARMA filter                                             */\n/* Internally operates as two biquad filters in sequence.               */\n\n/* Coeffients are stored in a packed format:                                                        */\n/*    { B1_Q14[1], B2_Q14[1], -A1_Q14[1], -A1_Q14[2], -A2_Q14[1], -A2_Q14[2], gain_Q16 }            */\n/* where it is assumed that B*_Q14[0], B*_Q14[2], A*_Q14[0] are all 16384                           */\n#if (EMBEDDED_ARM<5) \nvoid SKP_Silk_resampler_private_ARMA4(\n\tSKP_int32\t\t\t\t\t    S[],\t\t    /* I/O: State vector [ 4 ]\t\t\t    \t    */\n\tSKP_int16\t\t\t\t\t    out[],\t\t    /* O:\tOutput signal\t\t\t\t    \t    */\n\tconst SKP_int16\t\t\t\t    in[],\t\t\t/* I:\tInput signal\t\t\t\t    \t    */\n\tconst SKP_int16\t\t\t\t    Coef[],\t\t    /* I:\tARMA coefficients [ 7 ]                 */\n\tSKP_int32\t\t\t\t        len\t\t\t\t/* I:\tSignal length\t\t\t\t        \t*/\n)\n{\n\tSKP_int32 k;\n\tSKP_int32 in_Q8, out1_Q8, out2_Q8, X;\n\n\tfor( k = 0; k < len; k++ ) {\n        in_Q8  = SKP_LSHIFT32( (SKP_int32)in[ k ], 8 );\n\n        /* Outputs of first and second biquad */\n        out1_Q8 = SKP_ADD_LSHIFT32( in_Q8,   S[ 0 ], 2 );\n        out2_Q8 = SKP_ADD_LSHIFT32( out1_Q8, S[ 2 ], 2 );\n\n        /* Update states, which are stored in Q6. Coefficients are in Q14 here */\n        X      = SKP_SMLAWB( S[ 1 ], in_Q8,   Coef[ 0 ] );\n        S[ 0 ] = SKP_SMLAWB( X,      out1_Q8, Coef[ 2 ] );\n\n        X      = SKP_SMLAWB( S[ 3 ], out1_Q8, Coef[ 1 ] );\n        S[ 2 ] = SKP_SMLAWB( X,      out2_Q8, Coef[ 4 ] );\n\n        S[ 1 ] = SKP_SMLAWB( SKP_RSHIFT32( in_Q8,   2 ), out1_Q8, Coef[ 3 ] );\n        S[ 3 ] = SKP_SMLAWB( SKP_RSHIFT32( out1_Q8, 2 ), out2_Q8, Coef[ 5 ] );\n\n        /* Apply gain and store to output. The coefficient is in Q16 */\n        out[ k ] = (SKP_int16)SKP_SAT16( SKP_RSHIFT32( SKP_SMLAWB( 128, out2_Q8, Coef[ 6 ] ), 8 ) );\n\t}\n}\n#endif\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler_private_IIR_FIR.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * File Name:\tSKP_Silk_resampler_private_IIR_FIR.c  \t\t\t    *\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * Description: Hybrid IIR/FIR polyphase implementation of resampling\t*\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n * All rights reserved.\t\t\t\t\t\t\t\t\t\t\t\t\t*\n *                                                                      */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_resampler_private.h\"\n#if EMBEDDED_ARM<5\nSKP_INLINE SKP_int16 *SKP_Silk_resampler_private_IIR_FIR_INTERPOL( \n\t\t\tSKP_int16 * out, SKP_int16 * buf, SKP_int32 max_index_Q16 , SKP_int32 index_increment_Q16 ){\n\tSKP_int32 index_Q16, res_Q15;\n\tSKP_int16 *buf_ptr;\n\tSKP_int32 table_index;\n\t/* Interpolate upsampled signal and store in output array */\n\tfor( index_Q16 = 0; index_Q16 < max_index_Q16; index_Q16 += index_increment_Q16 ) {\n        table_index = SKP_SMULWB( index_Q16 & 0xFFFF, 144 );\n        buf_ptr = &buf[ index_Q16 >> 16 ];\n            \n        res_Q15 = SKP_SMULBB(          buf_ptr[ 0 ], SKP_Silk_resampler_frac_FIR_144[       table_index ][ 0 ] );\n        res_Q15 = SKP_SMLABB( res_Q15, buf_ptr[ 1 ], SKP_Silk_resampler_frac_FIR_144[       table_index ][ 1 ] );\n        res_Q15 = SKP_SMLABB( res_Q15, buf_ptr[ 2 ], SKP_Silk_resampler_frac_FIR_144[       table_index ][ 2 ] );\n        res_Q15 = SKP_SMLABB( res_Q15, buf_ptr[ 3 ], SKP_Silk_resampler_frac_FIR_144[ 143 - table_index ][ 2 ] );\n        res_Q15 = SKP_SMLABB( res_Q15, buf_ptr[ 4 ], SKP_Silk_resampler_frac_FIR_144[ 143 - table_index ][ 1 ] );\n        res_Q15 = SKP_SMLABB( res_Q15, buf_ptr[ 5 ], SKP_Silk_resampler_frac_FIR_144[ 143 - table_index ][ 0 ] );          \n\t\t*out++ = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( res_Q15, 15 ) );\n\t}\n\treturn out;\t\n}\n#else\nextern SKP_int16 *SKP_Silk_resampler_private_IIR_FIR_INTERPOL( \n\t\t\tSKP_int16 * out, SKP_int16 * buf, SKP_int32 max_index_Q16 , SKP_int32 index_increment_Q16 );\n#endif\n/* Upsample using a combination of allpass-based 2x upsampling and FIR interpolation */\nvoid SKP_Silk_resampler_private_IIR_FIR(\n\tvoid\t                        *SS,\t\t    /* I/O: Resampler state \t\t\t\t\t\t*/\n\tSKP_int16\t\t\t\t\t\tout[],\t\t    /* O:\tOutput signal \t\t\t\t\t\t\t*/\n\tconst SKP_int16\t\t\t\t\tin[],\t\t    /* I:\tInput signal\t\t\t\t\t\t\t*/\n\tSKP_int32\t\t\t\t\t    inLen\t\t    /* I:\tNumber of input samples\t\t\t\t\t*/\n)\n{\n    SKP_Silk_resampler_state_struct *S = (SKP_Silk_resampler_state_struct *)SS;\n\tSKP_int32 nSamplesIn;\n\tSKP_int32 max_index_Q16, index_increment_Q16;\n\tSKP_int16 buf[ 2 * RESAMPLER_MAX_BATCH_SIZE_IN + RESAMPLER_ORDER_FIR_144 ];\n    \n\n\t/* Copy buffered samples to start of buffer */\t\n\tSKP_memcpy( buf, S->sFIR, RESAMPLER_ORDER_FIR_144 * sizeof( SKP_int32 ) );\n\n\t/* Iterate over blocks of frameSizeIn input samples */\n    index_increment_Q16 = S->invRatio_Q16;\n\twhile( 1 ) {\n\t\tnSamplesIn = SKP_min( inLen, S->batchSize );\n\n        if( S->input2x == 1 ) {\n\t\t    /* Upsample 2x */\n            S->up2_function( S->sIIR, &buf[ RESAMPLER_ORDER_FIR_144 ], in, nSamplesIn );\n        } else {\n\t\t    /* Fourth-order ARMA filter */\n            SKP_Silk_resampler_private_ARMA4( S->sIIR, &buf[ RESAMPLER_ORDER_FIR_144 ], in, S->Coefs, nSamplesIn );\n        }\n\n        max_index_Q16 = SKP_LSHIFT32( nSamplesIn, 16 + S->input2x );         /* +1 if 2x upsampling */\n\t\tout = SKP_Silk_resampler_private_IIR_FIR_INTERPOL(out, buf, max_index_Q16, index_increment_Q16);    \n\t\tin += nSamplesIn;\n\t\tinLen -= nSamplesIn;\n\n\t\tif( inLen > 0 ) {\n\t\t\t/* More iterations to do; copy last part of filtered signal to beginning of buffer */\n\t\t\tSKP_memcpy( buf, &buf[ nSamplesIn << S->input2x ], RESAMPLER_ORDER_FIR_144 * sizeof( SKP_int32 ) );\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* Copy last part of filtered signal to the state for the next call */\n\tSKP_memcpy( S->sFIR, &buf[nSamplesIn << S->input2x ], RESAMPLER_ORDER_FIR_144 * sizeof( SKP_int32 ) );\n}\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler_private_copy.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * File Name:\tSKP_Silk_resampler_private_copy.c                     *\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * Description: Copy.                                                   *\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n * All rights reserved.\t\t\t\t\t\t\t\t\t\t\t\t\t*\n *                                                                      */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_resampler_private.h\"\n\n/* Copy */\nvoid SKP_Silk_resampler_private_copy(\n\tvoid\t                        *SS,\t\t    /* I/O: Resampler state (unused)\t\t\t\t*/\n\tSKP_int16\t\t\t\t\t\tout[],\t\t    /* O:\tOutput signal \t\t\t\t\t\t\t*/\n\tconst SKP_int16\t\t\t\t\tin[],\t\t    /* I:\tInput signal\t\t\t\t\t\t\t*/\n\tSKP_int32\t\t\t\t\t    inLen\t\t    /* I:\tNumber of input samples\t\t\t\t\t*/\n)\n{\n    SKP_memcpy( out, in, inLen * sizeof( SKP_int16 ) );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler_private_down4.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_resampler_private_down4.c                                 *\n *                                                                      *\n * Downsample by a factor 4                                             *\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n *                                                                      */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_resampler_private.h\"\n\n/* Downsample by a factor 4. Note: very low quality, only use with input sampling rates above 96 kHz. */\nvoid SKP_Silk_resampler_private_down4(\n    SKP_int32                       *S,             /* I/O: State vector [ 2 ]                      */\n    SKP_int16                       *out,           /* O:   Output signal [ floor(len/2) ]          */\n    const SKP_int16                 *in,            /* I:   Input signal [ len ]                    */\n    SKP_int32                       inLen           /* I:   Number of input samples                 */\n)\n{\n    SKP_int32 k, len4 = SKP_RSHIFT32( inLen, 2 );\n    SKP_int32 in32, out32, Y, X;\n\n    SKP_assert( SKP_Silk_resampler_down2_0 > 0 );\n    SKP_assert( SKP_Silk_resampler_down2_1 < 0 );\n\n    /* Internal variables and state are in Q10 format */\n    for( k = 0; k < len4; k++ ) {\n        /* Add two input samples and convert to Q10 */\n        in32 = SKP_LSHIFT( SKP_ADD32( (SKP_int32)in[ 4 * k ], (SKP_int32)in[ 4 * k + 1 ] ), 9 );\n\n        /* All-pass section for even input sample */\n        Y      = SKP_SUB32( in32, S[ 0 ] );\n        X      = SKP_SMLAWB( Y, Y, SKP_Silk_resampler_down2_1 );\n        out32  = SKP_ADD32( S[ 0 ], X );\n        S[ 0 ] = SKP_ADD32( in32, X );\n\n        /* Add two input samples and convert to Q10 */\n        in32 = SKP_LSHIFT( SKP_ADD32( (SKP_int32)in[ 4 * k + 2 ], (SKP_int32)in[ 4 * k + 3 ] ), 9 );\n\n        /* All-pass section for odd input sample */\n        Y      = SKP_SUB32( in32, S[ 1 ] );\n        X      = SKP_SMULWB( Y, SKP_Silk_resampler_down2_0 );\n        out32  = SKP_ADD32( out32, S[ 1 ] );\n        out32  = SKP_ADD32( out32, X );\n        S[ 1 ] = SKP_ADD32( in32, X );\n\n        /* Add, convert back to int16 and store to output */\n        out[ k ] = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( out32, 11 ) );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler_private_down_FIR.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * File Name:\tSKP_Silk_resampler_private_down_FIR.c                 *\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * Description: Hybrid IIR/FIR polyphase implementation of resampling\t*\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n * All rights reserved.\t\t\t\t\t\t\t\t\t\t\t\t\t*\n *                                                                      */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_resampler_private.h\"\n#if EMBEDDED_ARM<5\nSKP_INLINE SKP_int16 *SKP_Silk_resampler_private_down_FIR_INTERPOL0(\n\tSKP_int16 *out, SKP_int32 *buf2, const SKP_int16 *FIR_Coefs, SKP_int32 max_index_Q16, SKP_int32 index_increment_Q16){\n\t\n\tSKP_int32 index_Q16, res_Q6;\n\tSKP_int32 *buf_ptr;\n\tfor( index_Q16 = 0; index_Q16 < max_index_Q16; index_Q16 += index_increment_Q16 ) {\n\t\t/* Integer part gives pointer to buffered input */\n\t\tbuf_ptr = buf2 + SKP_RSHIFT( index_Q16, 16 );\n\n\t\t/* Inner product */\n\t\tres_Q6 = SKP_SMULWB(         SKP_ADD32( buf_ptr[ 0 ], buf_ptr[ 11 ] ), FIR_Coefs[ 0 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, SKP_ADD32( buf_ptr[ 1 ], buf_ptr[ 10 ] ), FIR_Coefs[ 1 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, SKP_ADD32( buf_ptr[ 2 ], buf_ptr[  9 ] ), FIR_Coefs[ 2 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, SKP_ADD32( buf_ptr[ 3 ], buf_ptr[  8 ] ), FIR_Coefs[ 3 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, SKP_ADD32( buf_ptr[ 4 ], buf_ptr[  7 ] ), FIR_Coefs[ 4 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, SKP_ADD32( buf_ptr[ 5 ], buf_ptr[  6 ] ), FIR_Coefs[ 5 ] );\n\n\t\t\t    /* Scale down, saturate and store in output array */\n\t\t*out++ = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( res_Q6, 6 ) );\n\t}\n\treturn out;\n}\n\nSKP_INLINE SKP_int16 *SKP_Silk_resampler_private_down_FIR_INTERPOL1(\n\tSKP_int16 *out, SKP_int32 *buf2, const SKP_int16 *FIR_Coefs, SKP_int32 max_index_Q16, SKP_int32 index_increment_Q16, SKP_int32 FIR_Fracs){\n\t\n\tSKP_int32 index_Q16, res_Q6;\n\tSKP_int32 *buf_ptr;\n\tSKP_int32 interpol_ind;\n\tconst SKP_int16 *interpol_ptr;\n\tfor( index_Q16 = 0; index_Q16 < max_index_Q16; index_Q16 += index_increment_Q16 ) {\n\t\t/* Integer part gives pointer to buffered input */\n\t\tbuf_ptr = buf2 + SKP_RSHIFT( index_Q16, 16 );\n\n\t\t/* Fractional part gives interpolation coefficients */\n\t\tinterpol_ind = SKP_SMULWB( index_Q16 & 0xFFFF, FIR_Fracs );\n\n\t\t/* Inner product */\n\t\tinterpol_ptr = &FIR_Coefs[ RESAMPLER_DOWN_ORDER_FIR / 2 * interpol_ind ];\n\t\tres_Q6 = SKP_SMULWB(         buf_ptr[ 0 ], interpol_ptr[ 0 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[ 1 ], interpol_ptr[ 1 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[ 2 ], interpol_ptr[ 2 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[ 3 ], interpol_ptr[ 3 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[ 4 ], interpol_ptr[ 4 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[ 5 ], interpol_ptr[ 5 ] );\n\t\tinterpol_ptr = &FIR_Coefs[ RESAMPLER_DOWN_ORDER_FIR / 2 * ( FIR_Fracs - 1 - interpol_ind ) ];\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[ 11 ], interpol_ptr[ 0 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[ 10 ], interpol_ptr[ 1 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[  9 ], interpol_ptr[ 2 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[  8 ], interpol_ptr[ 3 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[  7 ], interpol_ptr[ 4 ] );\n\t\tres_Q6 = SKP_SMLAWB( res_Q6, buf_ptr[  6 ], interpol_ptr[ 5 ] );\n\n\t\t/* Scale down, saturate and store in output array */\n\t\t*out++ = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( res_Q6, 6 ) );\n\t}\n\treturn out;\n}\n\n#else\nextern SKP_int16 *SKP_Silk_resampler_private_down_FIR_INTERPOL0(\n\tSKP_int16 *out, SKP_int32 *buf2, const SKP_int16 *FIR_Coefs, SKP_int32 max_index_Q16, SKP_int32 index_increment_Q16);\nextern SKP_int16 *SKP_Silk_resampler_private_down_FIR_INTERPOL1(\n\tSKP_int16 *out, SKP_int32 *buf2, const SKP_int16 *FIR_Coefs, SKP_int32 max_index_Q16, SKP_int32 index_increment_Q16, SKP_int32 FIR_Fracs);\t\n#endif\n\n/* Resample with a 2x downsampler (optional), a 2nd order AR filter followed by FIR interpolation */\nvoid SKP_Silk_resampler_private_down_FIR(\n\tvoid\t                        *SS,\t\t    /* I/O: Resampler state \t\t\t\t\t\t*/\n\tSKP_int16\t\t\t\t\t\tout[],\t\t    /* O:\tOutput signal \t\t\t\t\t\t\t*/\n\tconst SKP_int16\t\t\t\t\tin[],\t\t    /* I:\tInput signal\t\t\t\t\t\t\t*/\n\tSKP_int32\t\t\t\t\t    inLen\t\t    /* I:\tNumber of input samples\t\t\t\t\t*/\n)\n{\n    SKP_Silk_resampler_state_struct *S = (SKP_Silk_resampler_state_struct *)SS;\n\tSKP_int32 nSamplesIn;\n\tSKP_int32 max_index_Q16, index_increment_Q16;\n\tSKP_int16 buf1[ RESAMPLER_MAX_BATCH_SIZE_IN / 2 ];\n\tSKP_int32 buf2[ RESAMPLER_MAX_BATCH_SIZE_IN + RESAMPLER_DOWN_ORDER_FIR ];\n\tconst SKP_int16 *FIR_Coefs;\n\n\t/* Copy buffered samples to start of buffer */\t\n\tSKP_memcpy( buf2, S->sFIR, RESAMPLER_DOWN_ORDER_FIR * sizeof( SKP_int32 ) );\n\n    FIR_Coefs = &S->Coefs[ 2 ];\n\n\t/* Iterate over blocks of frameSizeIn input samples */\n    index_increment_Q16 = S->invRatio_Q16;\n\twhile( 1 ) {\n\t\tnSamplesIn = SKP_min( inLen, S->batchSize );\n\n        if( S->input2x == 1 ) {\n            /* Downsample 2x */\n            SKP_Silk_resampler_down2( S->sDown2, buf1, in, nSamplesIn );\n\n            nSamplesIn = SKP_RSHIFT32( nSamplesIn, 1 );\n\n\t\t    /* Second-order AR filter (output in Q8) */\n\t\t    SKP_Silk_resampler_private_AR2( S->sIIR, &buf2[ RESAMPLER_DOWN_ORDER_FIR ], buf1, S->Coefs, nSamplesIn );\n        } else {\n\t\t    /* Second-order AR filter (output in Q8) */\n\t\t    SKP_Silk_resampler_private_AR2( S->sIIR, &buf2[ RESAMPLER_DOWN_ORDER_FIR ], in, S->Coefs, nSamplesIn );\n        }\n\n        max_index_Q16 = SKP_LSHIFT32( nSamplesIn, 16 );\n\n\t\t/* Interpolate filtered signal */\n        if( S->FIR_Fracs == 1 ) {\n    \t\tout = SKP_Silk_resampler_private_down_FIR_INTERPOL0(out, buf2, FIR_Coefs, max_index_Q16, index_increment_Q16);\n        } else {\n    \t\tout = SKP_Silk_resampler_private_down_FIR_INTERPOL1(out, buf2, FIR_Coefs, max_index_Q16, index_increment_Q16, S->FIR_Fracs);\n        }\n        \n\t\tin += nSamplesIn << S->input2x;\n\t\tinLen -= nSamplesIn << S->input2x;\n\n\t\tif( inLen > S->input2x ) {\n\t\t\t/* More iterations to do; copy last part of filtered signal to beginning of buffer */\n\t\t\tSKP_memcpy( buf2, &buf2[ nSamplesIn ], RESAMPLER_DOWN_ORDER_FIR * sizeof( SKP_int32 ) );\n\t\t} else {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/* Copy last part of filtered signal to the state for the next call */\n\tSKP_memcpy( S->sFIR, &buf2[ nSamplesIn ], RESAMPLER_DOWN_ORDER_FIR * sizeof( SKP_int32 ) );\n}\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler_private_up2_HQ.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_resampler_private_up2_HQ.c                                *\n *                                                                      *\n * Upsample by a factor 2, high quality                                 *\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n *                                                                      */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_resampler_private.h\"\n\n/* Upsample by a factor 2, high quality */\n/* Uses 2nd order allpass filters for the 2x upsampling, followed by a      */\n/* notch filter just above Nyquist.                                         */\n#if (EMBEDDED_ARM<5) \nvoid SKP_Silk_resampler_private_up2_HQ(\n\tSKP_int32\t                    *S,\t\t\t    /* I/O: Resampler state [ 6 ]\t\t\t\t\t*/\n    SKP_int16                       *out,           /* O:   Output signal [ 2 * len ]               */\n    const SKP_int16                 *in,            /* I:   Input signal [ len ]                    */\n    SKP_int32                       len             /* I:   Number of INPUT samples                 */\n)\n{\n    SKP_int32 k;\n    SKP_int32 in32, out32_1, out32_2, Y, X;\n\n    SKP_assert( SKP_Silk_resampler_up2_hq_0[ 0 ] > 0 );\n    SKP_assert( SKP_Silk_resampler_up2_hq_0[ 1 ] < 0 );\n    SKP_assert( SKP_Silk_resampler_up2_hq_1[ 0 ] > 0 );\n    SKP_assert( SKP_Silk_resampler_up2_hq_1[ 1 ] < 0 );\n    \n    /* Internal variables and state are in Q10 format */\n    for( k = 0; k < len; k++ ) {\n        /* Convert to Q10 */\n        in32 = SKP_LSHIFT( (SKP_int32)in[ k ], 10 );\n\n        /* First all-pass section for even output sample */\n        Y       = SKP_SUB32( in32, S[ 0 ] );\n        X       = SKP_SMULWB( Y, SKP_Silk_resampler_up2_hq_0[ 0 ] );\n        out32_1 = SKP_ADD32( S[ 0 ], X );\n        S[ 0 ]  = SKP_ADD32( in32, X );\n\n        /* Second all-pass section for even output sample */\n        Y       = SKP_SUB32( out32_1, S[ 1 ] );\n        X       = SKP_SMLAWB( Y, Y, SKP_Silk_resampler_up2_hq_0[ 1 ] );\n        out32_2 = SKP_ADD32( S[ 1 ], X );\n        S[ 1 ]  = SKP_ADD32( out32_1, X );\n\n        /* Biquad notch filter */\n        out32_2 = SKP_SMLAWB( out32_2, S[ 5 ], SKP_Silk_resampler_up2_hq_notch[ 2 ] );\n        out32_2 = SKP_SMLAWB( out32_2, S[ 4 ], SKP_Silk_resampler_up2_hq_notch[ 1 ] );\n        out32_1 = SKP_SMLAWB( out32_2, S[ 4 ], SKP_Silk_resampler_up2_hq_notch[ 0 ] );\n        S[ 5 ]  = SKP_SUB32(  out32_2, S[ 5 ] );\n        \n        /* Apply gain in Q15, convert back to int16 and store to output */\n        out[ 2 * k ] = (SKP_int16)SKP_SAT16( SKP_RSHIFT32( \n            SKP_SMLAWB( 256, out32_1, SKP_Silk_resampler_up2_hq_notch[ 3 ] ), 9 ) );\n\n        /* First all-pass section for odd output sample */\n        Y       = SKP_SUB32( in32, S[ 2 ] );\n        X       = SKP_SMULWB( Y, SKP_Silk_resampler_up2_hq_1[ 0 ] );\n        out32_1 = SKP_ADD32( S[ 2 ], X );\n        S[ 2 ]  = SKP_ADD32( in32, X );\n\n        /* Second all-pass section for odd output sample */\n        Y       = SKP_SUB32( out32_1, S[ 3 ] );\n        X       = SKP_SMLAWB( Y, Y, SKP_Silk_resampler_up2_hq_1[ 1 ] );\n        out32_2 = SKP_ADD32( S[ 3 ], X );\n        S[ 3 ]  = SKP_ADD32( out32_1, X );\n\n        /* Biquad notch filter */\n        out32_2 = SKP_SMLAWB( out32_2, S[ 4 ], SKP_Silk_resampler_up2_hq_notch[ 2 ] );\n        out32_2 = SKP_SMLAWB( out32_2, S[ 5 ], SKP_Silk_resampler_up2_hq_notch[ 1 ] );\n        out32_1 = SKP_SMLAWB( out32_2, S[ 5 ], SKP_Silk_resampler_up2_hq_notch[ 0 ] );\n        S[ 4 ]  = SKP_SUB32(  out32_2, S[ 4 ] );\n        \n        /* Apply gain in Q15, convert back to int16 and store to output */\n        out[ 2 * k + 1 ] = (SKP_int16)SKP_SAT16( SKP_RSHIFT32( \n            SKP_SMLAWB( 256, out32_1, SKP_Silk_resampler_up2_hq_notch[ 3 ] ), 9 ) );\n    }\n}\n#endif\n\n\nvoid SKP_Silk_resampler_private_up2_HQ_wrapper(\n\tvoid\t                        *SS,\t\t    /* I/O: Resampler state (unused)\t\t\t\t*/\n    SKP_int16                       *out,           /* O:   Output signal [ 2 * len ]               */\n    const SKP_int16                 *in,            /* I:   Input signal [ len ]                    */\n    SKP_int32                       len             /* I:   Number of input samples                 */\n)\n{\n    SKP_Silk_resampler_state_struct *S = (SKP_Silk_resampler_state_struct *)SS;\n    SKP_Silk_resampler_private_up2_HQ( S->sIIR, out, in, len );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler_private_up4.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_resampler_private_up4.c                                   *\n *                                                                      *\n * Upsample by a factor 4, low quality                                  *\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n *                                                                      */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_resampler_private.h\"\n\n/* Upsample by a factor 4, Note: very low quality, only use with output sampling rates above 96 kHz. */\nvoid SKP_Silk_resampler_private_up4(\n    SKP_int32                       *S,             /* I/O: State vector [ 2 ]                      */\n    SKP_int16                       *out,           /* O:   Output signal [ 4 * len ]               */\n    const SKP_int16                 *in,            /* I:   Input signal [ len ]                    */\n    SKP_int32                       len             /* I:   Number of INPUT samples                 */\n)\n{\n    SKP_int32 k;\n    SKP_int32 in32, out32, Y, X;\n    SKP_int16 out16;\n\n    SKP_assert( SKP_Silk_resampler_up2_lq_0 > 0 );\n    SKP_assert( SKP_Silk_resampler_up2_lq_1 < 0 );\n\n    /* Internal variables and state are in Q10 format */\n    for( k = 0; k < len; k++ ) {\n        /* Convert to Q10 */\n        in32 = SKP_LSHIFT( (SKP_int32)in[ k ], 10 );\n\n        /* All-pass section for even output sample */\n        Y      = SKP_SUB32( in32, S[ 0 ] );\n        X      = SKP_SMULWB( Y, SKP_Silk_resampler_up2_lq_0 );\n        out32  = SKP_ADD32( S[ 0 ], X );\n        S[ 0 ] = SKP_ADD32( in32, X );\n\n        /* Convert back to int16 and store to output */\n        out16 = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( out32, 10 ) );\n        out[ 4 * k ]     = out16;\n        out[ 4 * k + 1 ] = out16;\n\n        /* All-pass section for odd output sample */\n        Y      = SKP_SUB32( in32, S[ 1 ] );\n        X      = SKP_SMLAWB( Y, Y, SKP_Silk_resampler_up2_lq_1 );\n        out32  = SKP_ADD32( S[ 1 ], X );\n        S[ 1 ] = SKP_ADD32( in32, X );\n\n        /* Convert back to int16 and store to output */\n        out16 = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( out32, 10 ) );\n        out[ 4 * k + 2 ] = out16;\n        out[ 4 * k + 3 ] = out16;\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler_rom.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * File Name:\tSKP_Silk_resampler_rom.c\t\t\t\t\t\t\t\t*\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * Description: Filter coefficients for IIR/FIR polyphase resampling\t*\n * Total size: 550 Words (1.1 kB)                                      *\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n * All rights reserved.\t\t\t\t\t\t\t\t\t\t\t\t\t*\n *                                                                      */\n\n#include \"SKP_Silk_resampler_private.h\"\n\n/* Tables for 2x downsampler */\nconst SKP_int16 SKP_Silk_resampler_down2_0 = 9872;\nconst SKP_int16 SKP_Silk_resampler_down2_1 = 39809 - 65536;\n\n/* Tables for 2x upsampler, low quality */\nconst SKP_int16 SKP_Silk_resampler_up2_lq_0 = 8102;\nconst SKP_int16 SKP_Silk_resampler_up2_lq_1 = 36783 - 65536;\n\n/* Tables for 2x upsampler, high quality */\nconst SKP_int16 SKP_Silk_resampler_up2_hq_0[ 2 ] = {  4280, 33727 - 65536 };\nconst SKP_int16 SKP_Silk_resampler_up2_hq_1[ 2 ] = { 16295, 54015 - 65536 };\n/* Matlab code for the notch filter coefficients: */\n/* B = [1, 0.12, 1];  A = [1, 0.055, 0.8]; G = 0.87; freqz(G * B, A, 2^14, 16e3); axis([0, 8000, -10, 1]);  */\n/* fprintf('\\t%6d, %6d, %6d, %6d\\n', round(B(2)*2^16), round(-A(2)*2^16), round((1-A(3))*2^16), round(G*2^15)) */\nconst SKP_int16 SKP_Silk_resampler_up2_hq_notch[ 4 ] = { 7864,  -3604,  13107,  28508 };\n\n\n/* Tables with IIR and FIR coefficients for fractional downsamplers (70 Words) */\nSKP_DWORD_ALIGN const SKP_int16 SKP_Silk_Resampler_3_4_COEFS[ 2 + 3 * RESAMPLER_DOWN_ORDER_FIR / 2 ] = {\n\t-18249, -12532,\n\t   -97,    284,   -495,    309,  10268,  20317,\n\t   -94,    156,    -48,   -720,   5984,  18278,\n\t   -45,     -4,    237,   -847,   2540,  14662,\n};\n\nSKP_DWORD_ALIGN const SKP_int16 SKP_Silk_Resampler_2_3_COEFS[ 2 + 2 * RESAMPLER_DOWN_ORDER_FIR / 2 ] = {\n\t-11891, -12486,\n\t    20,    211,   -657,    688,   8423,  15911,\n\t   -44,    197,   -152,   -653,   3855,  13015,\n};\n\nSKP_DWORD_ALIGN const SKP_int16 SKP_Silk_Resampler_1_2_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR / 2 ] = {\n\t  2415, -13101,\n\t   158,   -295,   -400,   1265,   4832,   7968,\n};\n\nSKP_DWORD_ALIGN const SKP_int16 SKP_Silk_Resampler_3_8_COEFS[ 2 + 3 * RESAMPLER_DOWN_ORDER_FIR / 2 ] = {\n\t 13270, -13738,\n\t  -294,   -123,    747,   2043,   3339,   3995,\n\t  -151,   -311,    414,   1583,   2947,   3877,\n\t   -33,   -389,    143,   1141,   2503,   3653,\n};\n\nSKP_DWORD_ALIGN const SKP_int16 SKP_Silk_Resampler_1_3_COEFS[ 2 + RESAMPLER_DOWN_ORDER_FIR / 2 ] = {\n\t 16643, -14000,\n\t  -331,     19,    581,   1421,   2290,   2845,\n};\n\nSKP_DWORD_ALIGN const SKP_int16 SKP_Silk_Resampler_2_3_COEFS_LQ[ 2 + 2 * 2 ] = {\n\t -2797,  -6507,\n\t  4697,  10739,\n\t  1567,   8276,\n};\n\nSKP_DWORD_ALIGN const SKP_int16 SKP_Silk_Resampler_1_3_COEFS_LQ[ 2 + 3 ] = {\n\t 16777,  -9792,\n\t   890,   1614,   2148,\n};\n\n\n/* Tables with coefficients for 4th order ARMA filter (35 Words), in a packed format:       */\n/*    { B1_Q14[1], B2_Q14[1], -A1_Q14[1], -A1_Q14[2], -A2_Q14[1], -A2_Q14[2], gain_Q16 }    */\n/* where it is assumed that B*_Q14[0], B*_Q14[2], A*_Q14[0] are all 16384                   */\nSKP_DWORD_ALIGN const SKP_int16 SKP_Silk_Resampler_320_441_ARMA4_COEFS[ 7 ] = {\n\t 31454,  24746,  -9706,  -3386, -17911, -13243,  24797\n};\n\nSKP_DWORD_ALIGN const SKP_int16 SKP_Silk_Resampler_240_441_ARMA4_COEFS[ 7 ] = {\n\t 28721,  11254,   3189,  -2546,  -1495, -12618,  11562\n};\n\nSKP_DWORD_ALIGN const SKP_int16 SKP_Silk_Resampler_160_441_ARMA4_COEFS[ 7 ] = {\n\t 23492,  -6457,  14358,  -4856,  14654, -13008,   4456\n};\n\nSKP_DWORD_ALIGN const SKP_int16 SKP_Silk_Resampler_120_441_ARMA4_COEFS[ 7 ] = {\n\t 19311, -15569,  19489,  -6950,  21441, -13559,   2370\n};\n\nSKP_DWORD_ALIGN const SKP_int16 SKP_Silk_Resampler_80_441_ARMA4_COEFS[ 7 ] = {\n\t 13248, -23849,  24126,  -9486,  26806, -14286,   1065\n};\n\n/* Table with interplation fractions of 1/288 : 2/288 : 287/288 (432 Words) */\nSKP_DWORD_ALIGN const SKP_int16 SKP_Silk_resampler_frac_FIR_144[ 144 ][ RESAMPLER_ORDER_FIR_144 / 2 ] = {\n\t{ -647,  1884, 30078},\n\t{ -625,  1736, 30044},\n\t{ -603,  1591, 30005},\n\t{ -581,  1448, 29963},\n\t{ -559,  1308, 29917},\n\t{ -537,  1169, 29867},\n\t{ -515,  1032, 29813},\n\t{ -494,   898, 29755},\n\t{ -473,   766, 29693},\n\t{ -452,   636, 29627},\n\t{ -431,   508, 29558},\n\t{ -410,   383, 29484},\n\t{ -390,   260, 29407},\n\t{ -369,   139, 29327},\n\t{ -349,    20, 29242},\n\t{ -330,   -97, 29154},\n\t{ -310,  -211, 29062},\n\t{ -291,  -324, 28967},\n\t{ -271,  -434, 28868},\n\t{ -253,  -542, 28765},\n\t{ -234,  -647, 28659},\n\t{ -215,  -751, 28550},\n\t{ -197,  -852, 28436},\n\t{ -179,  -951, 28320},\n\t{ -162, -1048, 28200},\n\t{ -144, -1143, 28077},\n\t{ -127, -1235, 27950},\n\t{ -110, -1326, 27820},\n\t{  -94, -1414, 27687},\n\t{  -77, -1500, 27550},\n\t{  -61, -1584, 27410},\n\t{  -45, -1665, 27268},\n\t{  -30, -1745, 27122},\n\t{  -15, -1822, 26972},\n\t{    0, -1897, 26820},\n\t{   15, -1970, 26665},\n\t{   29, -2041, 26507},\n\t{   44, -2110, 26346},\n\t{   57, -2177, 26182},\n\t{   71, -2242, 26015},\n\t{   84, -2305, 25845},\n\t{   97, -2365, 25673},\n\t{  110, -2424, 25498},\n\t{  122, -2480, 25320},\n\t{  134, -2534, 25140},\n\t{  146, -2587, 24956},\n\t{  157, -2637, 24771},\n\t{  168, -2685, 24583},\n\t{  179, -2732, 24392},\n\t{  190, -2776, 24199},\n\t{  200, -2819, 24003},\n\t{  210, -2859, 23805},\n\t{  220, -2898, 23605},\n\t{  229, -2934, 23403},\n\t{  238, -2969, 23198},\n\t{  247, -3002, 22992},\n\t{  255, -3033, 22783},\n\t{  263, -3062, 22572},\n\t{  271, -3089, 22359},\n\t{  279, -3114, 22144},\n\t{  286, -3138, 21927},\n\t{  293, -3160, 21709},\n\t{  300, -3180, 21488},\n\t{  306, -3198, 21266},\n\t{  312, -3215, 21042},\n\t{  318, -3229, 20816},\n\t{  323, -3242, 20589},\n\t{  328, -3254, 20360},\n\t{  333, -3263, 20130},\n\t{  338, -3272, 19898},\n\t{  342, -3278, 19665},\n\t{  346, -3283, 19430},\n\t{  350, -3286, 19194},\n\t{  353, -3288, 18957},\n\t{  356, -3288, 18718},\n\t{  359, -3286, 18478},\n\t{  362, -3283, 18238},\n\t{  364, -3279, 17996},\n\t{  366, -3273, 17753},\n\t{  368, -3266, 17509},\n\t{  369, -3257, 17264},\n\t{  371, -3247, 17018},\n\t{  372, -3235, 16772},\n\t{  372, -3222, 16525},\n\t{  373, -3208, 16277},\n\t{  373, -3192, 16028},\n\t{  373, -3175, 15779},\n\t{  373, -3157, 15529},\n\t{  372, -3138, 15279},\n\t{  371, -3117, 15028},\n\t{  370, -3095, 14777},\n\t{  369, -3072, 14526},\n\t{  368, -3048, 14274},\n\t{  366, -3022, 14022},\n\t{  364, -2996, 13770},\n\t{  362, -2968, 13517},\n\t{  359, -2940, 13265},\n\t{  357, -2910, 13012},\n\t{  354, -2880, 12760},\n\t{  351, -2848, 12508},\n\t{  348, -2815, 12255},\n\t{  344, -2782, 12003},\n\t{  341, -2747, 11751},\n\t{  337, -2712, 11500},\n\t{  333, -2676, 11248},\n\t{  328, -2639, 10997},\n\t{  324, -2601, 10747},\n\t{  320, -2562, 10497},\n\t{  315, -2523, 10247},\n\t{  310, -2482,  9998},\n\t{  305, -2442,  9750},\n\t{  300, -2400,  9502},\n\t{  294, -2358,  9255},\n\t{  289, -2315,  9009},\n\t{  283, -2271,  8763},\n\t{  277, -2227,  8519},\n\t{  271, -2182,  8275},\n\t{  265, -2137,  8032},\n\t{  259, -2091,  7791},\n\t{  252, -2045,  7550},\n\t{  246, -1998,  7311},\n\t{  239, -1951,  7072},\n\t{  232, -1904,  6835},\n\t{  226, -1856,  6599},\n\t{  219, -1807,  6364},\n\t{  212, -1758,  6131},\n\t{  204, -1709,  5899},\n\t{  197, -1660,  5668},\n\t{  190, -1611,  5439},\n\t{  183, -1561,  5212},\n\t{  175, -1511,  4986},\n\t{  168, -1460,  4761},\n\t{  160, -1410,  4538},\n\t{  152, -1359,  4317},\n\t{  145, -1309,  4098},\n\t{  137, -1258,  3880},\n\t{  129, -1207,  3664},\n\t{  121, -1156,  3450},\n\t{  113, -1105,  3238},\n\t{  105, -1054,  3028},\n\t{   97, -1003,  2820},\n\t{   89,  -952,  2614},\n\t{   81,  -901,  2409},\n\t{   73,  -851,  2207},\n};\n"
  },
  {
    "path": "app/jni/SKP_Silk_resampler_up2.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_resampler_up2.c                                           *\n *                                                                      *\n * Upsample by a factor 2, low quality                                  *\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n *                                                                      */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_resampler_rom.h\"\n\n/* Upsample by a factor 2, low quality */\n#if EMBEDDED_ARM<5\nvoid SKP_Silk_resampler_up2(\n    SKP_int32                           *S,         /* I/O: State vector [ 2 ]                  */\n    SKP_int16                           *out,       /* O:   Output signal [ 2 * len ]           */\n    const SKP_int16                     *in,        /* I:   Input signal [ len ]                */\n    SKP_int32                           len         /* I:   Number of input samples             */\n)\n{\n    SKP_int32 k;\n    SKP_int32 in32, out32, Y, X;\n\n    SKP_assert( SKP_Silk_resampler_up2_lq_0 > 0 );\n    SKP_assert( SKP_Silk_resampler_up2_lq_1 < 0 );\n    /* Internal variables and state are in Q10 format */\n    for( k = 0; k < len; k++ ) {\n        /* Convert to Q10 */\n        in32 = SKP_LSHIFT( (SKP_int32)in[ k ], 10 );\n\n        /* All-pass section for even output sample */\n        Y      = SKP_SUB32( in32, S[ 0 ] );\n        X      = SKP_SMULWB( Y, SKP_Silk_resampler_up2_lq_0 );\n        out32  = SKP_ADD32( S[ 0 ], X );\n        S[ 0 ] = SKP_ADD32( in32, X );\n\n        /* Convert back to int16 and store to output */\n        out[ 2 * k ] = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( out32, 10 ) );\n\n        /* All-pass section for odd output sample */\n        Y      = SKP_SUB32( in32, S[ 1 ] );\n        X      = SKP_SMLAWB( Y, Y, SKP_Silk_resampler_up2_lq_1 );\n        out32  = SKP_ADD32( S[ 1 ], X );\n        S[ 1 ] = SKP_ADD32( in32, X );\n\n        /* Convert back to int16 and store to output */\n        out[ 2 * k + 1 ] = (SKP_int16)SKP_SAT16( SKP_RSHIFT_ROUND( out32, 10 ) );\n    }\n}\n#endif\n"
  },
  {
    "path": "app/jni/SKP_Silk_residual_energy16_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\n/* Residual energy: nrg = wxx - 2 * wXx * c + c' * wXX * c */\nSKP_int32 SKP_Silk_residual_energy16_covar_FIX(\n    const SKP_int16                 *c,                 /* I    Prediction vector                           */\n    const SKP_int32                 *wXX,               /* I    Correlation matrix                          */\n    const SKP_int32                 *wXx,               /* I    Correlation vector                          */\n    SKP_int32                       wxx,                /* I    Signal energy                               */\n    SKP_int                         D,                  /* I    Dimension                                   */\n    SKP_int                         cQ                  /* I    Q value for c vector 0 - 15                 */\n)\n{\n    SKP_int   i, j, lshifts, Qxtra;\n    SKP_int32 c_max, w_max, tmp, tmp2, nrg;\n    SKP_int   cn[ MAX_MATRIX_SIZE ]; \n    const SKP_int32 *pRow;\n\n    /* Safety checks */\n    SKP_assert( D >=  0 );\n    SKP_assert( D <= 16 );\n    SKP_assert( cQ >  0 );\n    SKP_assert( cQ < 16 );\n\n    lshifts = 16 - cQ;\n    Qxtra = lshifts;\n\n    c_max = 0;\n    for( i = 0; i < D; i++ ) {\n        c_max = SKP_max_32( c_max, SKP_abs( ( SKP_int32 )c[ i ] ) );\n    }\n    Qxtra = SKP_min_int( Qxtra, SKP_Silk_CLZ32( c_max ) - 17 );\n\n    w_max = SKP_max_32( wXX[ 0 ], wXX[ D * D - 1 ] );\n    Qxtra = SKP_min_int( Qxtra, SKP_Silk_CLZ32( SKP_MUL( D, SKP_RSHIFT( SKP_SMULWB( w_max, c_max ), 4 ) ) ) - 5 );\n    Qxtra = SKP_max_int( Qxtra, 0 );\n    for( i = 0; i < D; i++ ) {\n        cn[ i ] = SKP_LSHIFT( ( SKP_int )c[ i ], Qxtra );\n        SKP_assert( SKP_abs(cn[i]) <= ( SKP_int16_MAX + 1 ) ); /* Check that SKP_SMLAWB can be used */\n    }\n    lshifts -= Qxtra;\n\n    /* Compute wxx - 2 * wXx * c */\n    tmp = 0;\n    for( i = 0; i < D; i++ ) {\n        tmp = SKP_SMLAWB( tmp, wXx[ i ], cn[ i ] );\n    }\n    nrg = SKP_RSHIFT( wxx, 1 + lshifts ) - tmp;                         /* Q: -lshifts - 1 */\n\n    /* Add c' * wXX * c, assuming wXX is symmetric */\n    tmp2 = 0;\n    for( i = 0; i < D; i++ ) {\n        tmp = 0;\n        pRow = &wXX[ i * D ];\n        for( j = i + 1; j < D; j++ ) {\n            tmp = SKP_SMLAWB( tmp, pRow[ j ], cn[ j ] );\n        }\n        tmp  = SKP_SMLAWB( tmp,  SKP_RSHIFT( pRow[ i ], 1 ), cn[ i ] );\n        tmp2 = SKP_SMLAWB( tmp2, tmp,                        cn[ i ] );\n    }\n    nrg = SKP_ADD_LSHIFT32( nrg, tmp2, lshifts );                       /* Q: -lshifts - 1 */\n\n    /* Keep one bit free always, because we add them for LSF interpolation */\n    if( nrg < 1 ) {\n        nrg = 1;\n    } else if( nrg > SKP_RSHIFT( SKP_int32_MAX, lshifts + 2 ) ) {\n        nrg = SKP_int32_MAX >> 1;\n    } else {\n        nrg = SKP_LSHIFT( nrg, lshifts + 1 );                           /* Q0 */\n    }\n    return nrg;\n\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_residual_energy_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\n/* Calculates residual energies of input subframes where all subframes have LPC_order   */\n/* of preceeding samples                                                                */\nvoid SKP_Silk_residual_energy_FIX(\n          SKP_int32 nrgs[ NB_SUBFR ],           /* O    Residual energy per subframe    */\n          SKP_int   nrgsQ[ NB_SUBFR ],          /* O    Q value per subframe            */\n    const SKP_int16 x[],                        /* I    Input signal                    */\n          SKP_int16 a_Q12[ 2 ][ MAX_LPC_ORDER ],/* I    AR coefs for each frame half    */\n    const SKP_int32 gains[ NB_SUBFR ],          /* I    Quantization gains              */\n    const SKP_int   subfr_length,               /* I    Subframe length                 */\n    const SKP_int   LPC_order                   /* I    LPC order                       */\n)\n{\n    SKP_int         offset, i, j, rshift, lz1, lz2;\n    SKP_int16       *LPC_res_ptr, LPC_res[ ( MAX_FRAME_LENGTH + NB_SUBFR * MAX_LPC_ORDER ) / 2 ];\n    const SKP_int16 *x_ptr;\n    SKP_int16       S[ MAX_LPC_ORDER ];\n    SKP_int32       tmp32;\n\n    x_ptr  = x;\n    offset = LPC_order + subfr_length;\n    \n    /* Filter input to create the LPC residual for each frame half, and measure subframe energies */\n    for( i = 0; i < 2; i++ ) {\n        /* Calculate half frame LPC residual signal including preceeding samples */\n        SKP_memset( S, 0, LPC_order * sizeof( SKP_int16 ) );\n        SKP_Silk_LPC_analysis_filter( x_ptr, a_Q12[ i ], S, LPC_res, ( NB_SUBFR >> 1 ) * offset, LPC_order );\n\n        /* Point to first subframe of the just calculated LPC residual signal */\n        LPC_res_ptr = LPC_res + LPC_order;\n        for( j = 0; j < ( NB_SUBFR >> 1 ); j++ ) {\n            /* Measure subframe energy */\n            SKP_Silk_sum_sqr_shift( &nrgs[ i * ( NB_SUBFR >> 1 ) + j ], &rshift, LPC_res_ptr, subfr_length ); \n            \n            /* Set Q values for the measured energy */\n            nrgsQ[ i * ( NB_SUBFR >> 1 ) + j ] = -rshift;\n            \n            /* Move to next subframe */\n            LPC_res_ptr += offset;\n        }\n        /* Move to next frame half */\n        x_ptr += ( NB_SUBFR >> 1 ) * offset;\n    }\n\n    /* Apply the squared subframe gains */\n    for( i = 0; i < NB_SUBFR; i++ ) {\n        /* Fully upscale gains and energies */\n        lz1 = SKP_Silk_CLZ32( nrgs[  i ] ) - 1; \n        lz2 = SKP_Silk_CLZ32( gains[ i ] ) - 1; \n        \n        tmp32 = SKP_LSHIFT32( gains[ i ], lz2 );\n\n        /* Find squared gains */\n        tmp32 = SKP_SMMUL( tmp32, tmp32 ); // Q( 2 * lz2 - 32 )\n\n        /* Scale energies */\n        nrgs[ i ] = SKP_SMMUL( tmp32, SKP_LSHIFT32( nrgs[ i ], lz1 ) ); // Q( nrgsQ[ i ] + lz1 + 2 * lz2 - 32 - 32 )\n        nrgsQ[ i ] += lz1 + 2 * lz2 - 32 - 32;\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_scale_copy_vector16.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Copy and multiply a vector by a constant */\nvoid SKP_Silk_scale_copy_vector16( \n    SKP_int16           *data_out, \n    const SKP_int16     *data_in, \n    SKP_int32           gain_Q16,                   /* (I):   gain in Q16   */\n    const SKP_int       dataSize                    /* (I):   length        */\n)\n{\n    SKP_int  i;\n    SKP_int32 tmp32;\n\n    for( i = 0; i < dataSize; i++ ) {\n        tmp32 = SKP_SMULWB( gain_Q16, data_in[ i ] );\n        data_out[ i ] = (SKP_int16)SKP_CHECK_FIT16( tmp32 );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_scale_vector.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Multiply a vector by a constant */\nvoid SKP_Silk_scale_vector32_Q26_lshift_18( \n    SKP_int32           *data1,                     /* (I/O): Q0/Q18        */\n    SKP_int32           gain_Q26,                   /* (I):   Q26           */\n    SKP_int             dataSize                    /* (I):   length        */\n)\n{\n    SKP_int  i;\n\n    for( i = 0; i < dataSize; i++ ) {\n        data1[ i ] = (SKP_int32)SKP_CHECK_FIT32( SKP_RSHIFT64( SKP_SMULL( data1[ i ], gain_Q26 ), 8 ) );// OUTPUT: Q18\n    }\n}\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_schur.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_schur.c                                                   *\n *                                                                      *\n * Calculates the reflection coefficients from the correlation sequence *\n *                                                                      *\n * Copyright 2008 (c), Skype Limited                                    *\n * Date: 080103                                                         *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Faster than schur64(), but much less accurate.                       */\n/* uses SMLAWB(), requiring armv5E and higher.                          */ \nSKP_int32 SKP_Silk_schur(                     /* O:    Returns residual energy                     */\n    SKP_int16            *rc_Q15,               /* O:    reflection coefficients [order] Q15         */\n    const SKP_int32      *c,                    /* I:    correlations [order+1]                      */\n    const SKP_int32      order                  /* I:    prediction order                            */\n)\n{\n    SKP_int        k, n, lz;\n    SKP_int32    C[ SKP_Silk_MAX_ORDER_LPC + 1 ][ 2 ];\n    SKP_int32    Ctmp1, Ctmp2, rc_tmp_Q15;\n\n    /* Get number of leading zeros */\n    lz = SKP_Silk_CLZ32( c[ 0 ] );\n\n    /* Copy correlations and adjust level to Q30 */\n    if( lz < 2 ) {\n        /* lz must be 1, so shift one to the right */\n        for( k = 0; k < order + 1; k++ ) {\n            C[ k ][ 0 ] = C[ k ][ 1 ] = SKP_RSHIFT( c[ k ], 1 );\n        }\n    } else if( lz > 2 ) {\n        /* Shift to the left */\n        lz -= 2; \n        for( k = 0; k < order + 1; k++ ) {\n            C[ k ][ 0 ] = C[ k ][ 1 ] = SKP_LSHIFT( c[k], lz );\n        }\n    } else {\n        /* No need to shift */\n        for( k = 0; k < order + 1; k++ ) {\n            C[ k ][ 0 ] = C[ k ][ 1 ] = c[ k ];\n        }\n    }\n\n    for( k = 0; k < order; k++ ) {\n        \n        /* Get reflection coefficient */\n        rc_tmp_Q15 = -SKP_DIV32_16( C[ k + 1 ][ 0 ], SKP_max_32( SKP_RSHIFT( C[ 0 ][ 1 ], 15 ), 1 ) );\n\n        /* Clip (shouldn't happen for properly conditioned inputs) */\n        rc_tmp_Q15 = SKP_SAT16( rc_tmp_Q15 );\n\n        /* Store */\n        rc_Q15[ k ] = (SKP_int16)rc_tmp_Q15;\n\n        /* Update correlations */\n        for( n = 0; n < order - k; n++ ) {\n            Ctmp1 = C[ n + k + 1 ][ 0 ];\n            Ctmp2 = C[ n ][ 1 ];\n            C[ n + k + 1 ][ 0 ] = SKP_SMLAWB( Ctmp1, SKP_LSHIFT( Ctmp2, 1 ), rc_tmp_Q15 );\n            C[ n ][ 1 ]         = SKP_SMLAWB( Ctmp2, SKP_LSHIFT( Ctmp1, 1 ), rc_tmp_Q15 );\n        }\n    }\n\n    /* return residual energy */\n    return C[0][1];\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_schur64.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_schur64.c                                                 *\n *                                                                      *\n * Calculates the reflection coefficients from the correlation sequence *\n * using extra precision                                                *\n *                                                                      *\n * Copyright 2008 (c), Skype Limited                                    *\n * Date: 080103                                                         *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Slower than schur(), but more accurate.                              */\n/* Uses SMULL(), available on armv4                                     */ \n#if EMBEDDED_ARM<6\nSKP_int32 SKP_Silk_schur64(                    /* O:    Returns residual energy                     */\n    SKP_int32            rc_Q16[],               /* O:    Reflection coefficients [order] Q16         */\n    const SKP_int32      c[],                    /* I:    Correlations [order+1]                      */\n    SKP_int32            order                   /* I:    Prediction order                            */\n)\n{\n    SKP_int   k, n;\n    SKP_int32 C[ SKP_Silk_MAX_ORDER_LPC + 1 ][ 2 ];\n    SKP_int32 Ctmp1_Q30, Ctmp2_Q30, rc_tmp_Q31;\n\n    /* Check for invalid input */\n    if( c[ 0 ] <= 0 ) {\n        SKP_memset( rc_Q16, 0, order * sizeof( SKP_int32 ) );\n        return 0;\n    }\n    \n    for( k = 0; k < order + 1; k++ ) {\n        C[ k ][ 0 ] = C[ k ][ 1 ] = c[ k ];\n    }\n\n    for( k = 0; k < order; k++ ) {\n        /* Get reflection coefficient: divide two Q30 values and get result in Q31 */\n        rc_tmp_Q31 = SKP_DIV32_varQ( -C[ k + 1 ][ 0 ], C[ 0 ][ 1 ], 31 );\n\n        /* Save the output */\n        rc_Q16[ k ] = SKP_RSHIFT_ROUND( rc_tmp_Q31, 15 );\n\n        /* Update correlations */\n        for( n = 0; n < order - k; n++ ) {\n            Ctmp1_Q30 = C[ n + k + 1 ][ 0 ];\n            Ctmp2_Q30 = C[ n ][ 1 ];\n            \n            /* Multiply and add the highest int32 */\n            C[ n + k + 1 ][ 0 ] = Ctmp1_Q30 + SKP_SMMUL( SKP_LSHIFT( Ctmp2_Q30, 1 ), rc_tmp_Q31 );\n            C[ n ][ 1 ]         = Ctmp2_Q30 + SKP_SMMUL( SKP_LSHIFT( Ctmp1_Q30, 1 ), rc_tmp_Q31 );\n        }\n    }\n\n    return C[ 0 ][ 1 ];\n}\n#endif\n"
  },
  {
    "path": "app/jni/SKP_Silk_shell_coder.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n\n/* shell coder; pulse-subframe length is hardcoded */\n\nSKP_INLINE void combine_pulses(\n    SKP_int         *out,   /* O:   combined pulses vector [len] */\n    const SKP_int   *in,    /* I:   input vector       [2 * len] */\n    const SKP_int   len     /* I:   number of OUTPUT samples     */\n)\n{\n    SKP_int k;\n    for( k = 0; k < len; k++ ) {\n        out[ k ] = in[ 2 * k ] + in[ 2 * k + 1 ];\n    }\n}\n\nSKP_INLINE void encode_split(\n    SKP_Silk_range_coder_state  *sRC,           /* I/O: compressor data structure                   */\n    const SKP_int               p_child1,       /* I:   pulse amplitude of first child subframe     */\n    const SKP_int               p,              /* I:   pulse amplitude of current subframe         */\n    const SKP_uint16            *shell_table    /* I:   table of shell cdfs                         */\n)\n{\n    const SKP_uint16 *cdf;\n\n    if( p > 0 ) {\n        cdf = &shell_table[ SKP_Silk_shell_code_table_offsets[ p ] ];\n        SKP_Silk_range_encoder( sRC, p_child1, cdf );\n    }\n}\n\nSKP_INLINE void decode_split(\n    SKP_int                     *p_child1,      /* O:   pulse amplitude of first child subframe     */\n    SKP_int                     *p_child2,      /* O:   pulse amplitude of second child subframe    */\n    SKP_Silk_range_coder_state  *sRC,           /* I/O: compressor data structure                   */\n    const SKP_int               p,              /* I:   pulse amplitude of current subframe         */\n    const SKP_uint16            *shell_table    /* I:   table of shell cdfs                         */\n)\n{\n    SKP_int cdf_middle;\n    const SKP_uint16 *cdf;\n\n    if( p > 0 ) {\n        cdf_middle = SKP_RSHIFT( p, 1 );\n        cdf = &shell_table[ SKP_Silk_shell_code_table_offsets[ p ] ];\n        SKP_Silk_range_decoder( p_child1, sRC, cdf, cdf_middle );\n        p_child2[ 0 ] = p - p_child1[ 0 ];\n    } else {\n        p_child1[ 0 ] = 0;\n        p_child2[ 0 ] = 0;\n    }\n}\n\n/* Shell encoder, operates on one shell code frame of 16 pulses */\nvoid SKP_Silk_shell_encoder(\n    SKP_Silk_range_coder_state      *sRC,               /* I/O  compressor data structure                   */\n    const SKP_int                   *pulses0            /* I    data: nonnegative pulse amplitudes          */\n)\n{\n    SKP_int pulses1[ 8 ], pulses2[ 4 ], pulses3[ 2 ], pulses4[ 1 ];\n\n    /* this function operates on one shell code frame of 16 pulses */\n    SKP_assert( SHELL_CODEC_FRAME_LENGTH == 16 );\n\n    /* tree representation per pulse-subframe */\n    combine_pulses( pulses1, pulses0, 8 );\n    combine_pulses( pulses2, pulses1, 4 );\n    combine_pulses( pulses3, pulses2, 2 );\n    combine_pulses( pulses4, pulses3, 1 );\n\n    encode_split( sRC, pulses3[  0 ], pulses4[ 0 ], SKP_Silk_shell_code_table3 );\n\n    encode_split( sRC, pulses2[  0 ], pulses3[ 0 ], SKP_Silk_shell_code_table2 );\n\n    encode_split( sRC, pulses1[  0 ], pulses2[ 0 ], SKP_Silk_shell_code_table1 );\n    encode_split( sRC, pulses0[  0 ], pulses1[ 0 ], SKP_Silk_shell_code_table0 );\n    encode_split( sRC, pulses0[  2 ], pulses1[ 1 ], SKP_Silk_shell_code_table0 );\n\n    encode_split( sRC, pulses1[  2 ], pulses2[ 1 ], SKP_Silk_shell_code_table1 );\n    encode_split( sRC, pulses0[  4 ], pulses1[ 2 ], SKP_Silk_shell_code_table0 );\n    encode_split( sRC, pulses0[  6 ], pulses1[ 3 ], SKP_Silk_shell_code_table0 );\n\n    encode_split( sRC, pulses2[  2 ], pulses3[ 1 ], SKP_Silk_shell_code_table2 );\n\n    encode_split( sRC, pulses1[  4 ], pulses2[ 2 ], SKP_Silk_shell_code_table1 );\n    encode_split( sRC, pulses0[  8 ], pulses1[ 4 ], SKP_Silk_shell_code_table0 );\n    encode_split( sRC, pulses0[ 10 ], pulses1[ 5 ], SKP_Silk_shell_code_table0 );\n\n    encode_split( sRC, pulses1[  6 ], pulses2[ 3 ], SKP_Silk_shell_code_table1 );\n    encode_split( sRC, pulses0[ 12 ], pulses1[ 6 ], SKP_Silk_shell_code_table0 );\n    encode_split( sRC, pulses0[ 14 ], pulses1[ 7 ], SKP_Silk_shell_code_table0 );\n}\n\n\n/* Shell decoder, operates on one shell code frame of 16 pulses */\nvoid SKP_Silk_shell_decoder(\n    SKP_int                         *pulses0,           /* O    data: nonnegative pulse amplitudes          */\n    SKP_Silk_range_coder_state      *sRC,               /* I/O  compressor data structure                   */\n    const SKP_int                   pulses4             /* I    number of pulses per pulse-subframe         */\n)\n{\n    SKP_int pulses3[ 2 ], pulses2[ 4 ], pulses1[ 8 ];\n\n    /* this function operates on one shell code frame of 16 pulses */\n    SKP_assert( SHELL_CODEC_FRAME_LENGTH == 16 );\n\n    decode_split( &pulses3[  0 ], &pulses3[  1 ], sRC, pulses4,      SKP_Silk_shell_code_table3 );\n\n    decode_split( &pulses2[  0 ], &pulses2[  1 ], sRC, pulses3[ 0 ], SKP_Silk_shell_code_table2 );\n\n    decode_split( &pulses1[  0 ], &pulses1[  1 ], sRC, pulses2[ 0 ], SKP_Silk_shell_code_table1 );\n    decode_split( &pulses0[  0 ], &pulses0[  1 ], sRC, pulses1[ 0 ], SKP_Silk_shell_code_table0 );\n    decode_split( &pulses0[  2 ], &pulses0[  3 ], sRC, pulses1[ 1 ], SKP_Silk_shell_code_table0 );\n\n    decode_split( &pulses1[  2 ], &pulses1[  3 ], sRC, pulses2[ 1 ], SKP_Silk_shell_code_table1 );\n    decode_split( &pulses0[  4 ], &pulses0[  5 ], sRC, pulses1[ 2 ], SKP_Silk_shell_code_table0 );\n    decode_split( &pulses0[  6 ], &pulses0[  7 ], sRC, pulses1[ 3 ], SKP_Silk_shell_code_table0 );\n\n    decode_split( &pulses2[  2 ], &pulses2[  3 ], sRC, pulses3[ 1 ], SKP_Silk_shell_code_table2 );\n\n    decode_split( &pulses1[  4 ], &pulses1[  5 ], sRC, pulses2[ 2 ], SKP_Silk_shell_code_table1 );\n    decode_split( &pulses0[  8 ], &pulses0[  9 ], sRC, pulses1[ 4 ], SKP_Silk_shell_code_table0 );\n    decode_split( &pulses0[ 10 ], &pulses0[ 11 ], sRC, pulses1[ 5 ], SKP_Silk_shell_code_table0 );\n\n    decode_split( &pulses1[  6 ], &pulses1[  7 ], sRC, pulses2[ 3 ], SKP_Silk_shell_code_table1 );\n    decode_split( &pulses0[ 12 ], &pulses0[ 13 ], sRC, pulses1[ 6 ], SKP_Silk_shell_code_table0 );\n    decode_split( &pulses0[ 14 ], &pulses0[ 15 ], sRC, pulses1[ 7 ], SKP_Silk_shell_code_table0 );\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_sigm_Q15.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_sigm_Q15.c                                                       *\n *                                                                      *\n * Approximate sigmoid function                                         *\n *                                                                      *\n * Copyright 2006 (c), Skype Limited                                    *\n * Date: 060221                                                         *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n#if EMBEDDED_ARM<4\n/********************************/\n/* approximate sigmoid function */\n/********************************/\n/* fprintf(1, '%d, ', round(1024 * ([1 ./ (1 + exp(-(1:5))), 1] - 1 ./ (1 + exp(-(0:5)))))); */\nstatic const SKP_int32 sigm_LUT_slope_Q10[ 6 ] = {\n    237, 153, 73, 30, 12, 7\n};\n/* fprintf(1, '%d, ', round(32767 * 1 ./ (1 + exp(-(0:5))))); */\nstatic const SKP_int32 sigm_LUT_pos_Q15[ 6 ] = {\n    16384, 23955, 28861, 31213, 32178, 32548\n};\n/* fprintf(1, '%d, ', round(32767 * 1 ./ (1 + exp((0:5))))); */\nstatic const SKP_int32 sigm_LUT_neg_Q15[ 6 ] = {\n    16384, 8812, 3906, 1554, 589, 219\n};\n\nSKP_int SKP_Silk_sigm_Q15( SKP_int in_Q5 ) \n{\n    SKP_int ind;\n\n    if( in_Q5 < 0 ) {\n        /* Negative input */\n        in_Q5 = -in_Q5;\n        if( in_Q5 >= 6 * 32 ) {\n            return 0;        /* Clip */\n        } else {\n            /* Linear interpolation of look up table */\n            ind = SKP_RSHIFT( in_Q5, 5 );\n            return( sigm_LUT_neg_Q15[ ind ] - SKP_SMULBB( sigm_LUT_slope_Q10[ ind ], in_Q5 & 0x1F ) );\n        }\n    } else {\n        /* Positive input */\n        if( in_Q5 >= 6 * 32 ) {\n            return 32767;        /* clip */\n        } else {\n            /* Linear interpolation of look up table */\n            ind = SKP_RSHIFT( in_Q5, 5 );\n            return( sigm_LUT_pos_Q15[ ind ] + SKP_SMULBB( sigm_LUT_slope_Q10[ ind ], in_Q5 & 0x1F ) );\n        }\n    }\n}\n#endif\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_solve_LS_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n#include \"SKP_Silk_tuning_parameters.h\"\n\n/*****************************/\n/* Internal function headers */\n/*****************************/\n\ntypedef struct {\n    SKP_int32 Q36_part;\n    SKP_int32 Q48_part;\n} inv_D_t;\n\n/* Factorize square matrix A into LDL form */\nSKP_INLINE void SKP_Silk_LDL_factorize_FIX(\n    SKP_int32           *A,         /* I/O Pointer to Symetric Square Matrix */\n    SKP_int             M,          /* I   Size of Matrix */\n    SKP_int32           *L_Q16,     /* I/O Pointer to Square Upper triangular Matrix */\n    inv_D_t             *inv_D      /* I/O Pointer to vector holding inverted diagonal elements of D */\n);\n\n/* Solve Lx = b, when L is lower triangular and has ones on the diagonal */\nSKP_INLINE void SKP_Silk_LS_SolveFirst_FIX(\n    const SKP_int32     *L_Q16,     /* I Pointer to Lower Triangular Matrix */\n    SKP_int             M,          /* I Dim of Matrix equation */\n    const SKP_int32     *b,         /* I b Vector */\n    SKP_int32           *x_Q16      /* O x Vector */  \n);\n\n/* Solve L^t*x = b, where L is lower triangular with ones on the diagonal */\nSKP_INLINE void SKP_Silk_LS_SolveLast_FIX(\n    const SKP_int32     *L_Q16,     /* I Pointer to Lower Triangular Matrix */\n    const SKP_int       M,          /* I Dim of Matrix equation */\n    const SKP_int32     *b,         /* I b Vector */\n    SKP_int32           *x_Q16      /* O x Vector */  \n);\n\nSKP_INLINE void SKP_Silk_LS_divide_Q16_FIX(\n    SKP_int32           T[],    /* I/O Numenator vector */\n    inv_D_t             *inv_D, /* I   1 / D vector     */\n    SKP_int             M       /* I   dimension        */\n);\n\n/* Solves Ax = b, assuming A is symmetric */\nvoid SKP_Silk_solve_LDL_FIX(\n    SKP_int32                       *A,                 /* I    Pointer to symetric square matrix A         */\n    SKP_int                         M,                  /* I    Size of matrix                              */\n    const SKP_int32                 *b,                 /* I    Pointer to b vector                         */\n    SKP_int32                       *x_Q16              /* O    Pointer to x solution vector                */\n)\n{\n    SKP_int32 L_Q16[  MAX_MATRIX_SIZE * MAX_MATRIX_SIZE ]; \n    SKP_int32 Y[      MAX_MATRIX_SIZE ];\n    inv_D_t   inv_D[  MAX_MATRIX_SIZE ];\n\n    SKP_assert( M <= MAX_MATRIX_SIZE );\n\n    /***************************************************\n    Factorize A by LDL such that A = L*D*L',\n    where L is lower triangular with ones on diagonal\n    ****************************************************/\n    SKP_Silk_LDL_factorize_FIX( A, M, L_Q16, inv_D );\n        \n    /****************************************************\n    * substitute D*L'*x = Y. ie:\n    L*D*L'*x = b => L*Y = b <=> Y = inv(L)*b\n    ******************************************************/\n    SKP_Silk_LS_SolveFirst_FIX( L_Q16, M, b, Y );\n\n    /****************************************************\n    D*L'*x = Y <=> L'*x = inv(D)*Y, because D is \n    diagonal just multiply with 1/d_i\n    ****************************************************/\n    SKP_Silk_LS_divide_Q16_FIX( Y, inv_D, M );\n\n    /****************************************************\n    x = inv(L') * inv(D) * Y\n    *****************************************************/\n    SKP_Silk_LS_SolveLast_FIX( L_Q16, M, Y, x_Q16 );\n}\n\nSKP_INLINE void SKP_Silk_LDL_factorize_FIX(\n    SKP_int32           *A,         /* I   Pointer to Symetric Square Matrix */\n    SKP_int             M,          /* I   Size of Matrix */\n    SKP_int32           *L_Q16,     /* I/O Pointer to Square Upper triangular Matrix */\n    inv_D_t             *inv_D      /* I/O Pointer to vector holding inverted diagonal elements of D */\n)\n{\n    SKP_int   i, j, k, status, loop_count;\n    const SKP_int32 *ptr1, *ptr2;\n    SKP_int32 diag_min_value, tmp_32, err;\n    SKP_int32 v_Q0[ MAX_MATRIX_SIZE ], D_Q0[ MAX_MATRIX_SIZE ];\n    SKP_int32 one_div_diag_Q36, one_div_diag_Q40, one_div_diag_Q48;\n\n    SKP_assert( M <= MAX_MATRIX_SIZE );\n\n    status = 1;\n    diag_min_value = SKP_max_32( SKP_SMMUL( SKP_ADD_SAT32( A[ 0 ], A[ SKP_SMULBB( M, M ) - 1 ] ), SKP_FIX_CONST( FIND_LTP_COND_FAC, 31 ) ), 1 << 9 );\n    for( loop_count = 0; loop_count < M && status == 1; loop_count++ ) {\n        status = 0;\n        for( j = 0; j < M; j++ ) {\n            ptr1 = matrix_adr( L_Q16, j, 0, M );\n            tmp_32 = 0;\n            for( i = 0; i < j; i++ ) {\n                v_Q0[ i ] = SKP_SMULWW(         D_Q0[ i ], ptr1[ i ] ); /* Q0 */\n                tmp_32    = SKP_SMLAWW( tmp_32, v_Q0[ i ], ptr1[ i ] ); /* Q0 */\n            }\n            tmp_32 = SKP_SUB32( matrix_ptr( A, j, j, M ), tmp_32 );\n\n            if( tmp_32 < diag_min_value ) {\n                tmp_32 = SKP_SUB32( SKP_SMULBB( loop_count + 1, diag_min_value ), tmp_32 );\n                /* Matrix not positive semi-definite, or ill conditioned */\n                for( i = 0; i < M; i++ ) {\n                    matrix_ptr( A, i, i, M ) = SKP_ADD32( matrix_ptr( A, i, i, M ), tmp_32 );\n                }\n                status = 1;\n                break;\n            }\n            D_Q0[ j ] = tmp_32;                         /* always < max(Correlation) */\n        \n            /* two-step division */\n            one_div_diag_Q36 = SKP_INVERSE32_varQ( tmp_32, 36 );                    /* Q36 */\n            one_div_diag_Q40 = SKP_LSHIFT( one_div_diag_Q36, 4 );                   /* Q40 */\n            err = SKP_SUB32( 1 << 24, SKP_SMULWW( tmp_32, one_div_diag_Q40 ) );     /* Q24 */\n            one_div_diag_Q48 = SKP_SMULWW( err, one_div_diag_Q40 );                 /* Q48 */\n\n            /* Save 1/Ds */\n            inv_D[ j ].Q36_part = one_div_diag_Q36;\n            inv_D[ j ].Q48_part = one_div_diag_Q48;\n\n            matrix_ptr( L_Q16, j, j, M ) = 65536; /* 1.0 in Q16 */\n            ptr1 = matrix_adr( A, j, 0, M );\n            ptr2 = matrix_adr( L_Q16, j + 1, 0, M );\n            for( i = j + 1; i < M; i++ ) { \n                tmp_32 = 0;\n                for( k = 0; k < j; k++ ) {\n                    tmp_32 = SKP_SMLAWW( tmp_32, v_Q0[ k ], ptr2[ k ] ); /* Q0 */\n                }\n                tmp_32 = SKP_SUB32( ptr1[ i ], tmp_32 ); /* always < max(Correlation) */\n\n                /* tmp_32 / D_Q0[j] : Divide to Q16 */\n                matrix_ptr( L_Q16, i, j, M ) = SKP_ADD32( SKP_SMMUL( tmp_32, one_div_diag_Q48 ),\n                    SKP_RSHIFT( SKP_SMULWW( tmp_32, one_div_diag_Q36 ), 4 ) );\n\n                /* go to next column */\n                ptr2 += M; \n            }\n        }\n    }\n\n    SKP_assert( status == 0 );\n}\n\nSKP_INLINE void SKP_Silk_LS_divide_Q16_FIX(\n    SKP_int32 T[],      /* I/O Numenator vector */\n    inv_D_t *inv_D,     /* I   1 / D vector     */\n    SKP_int M           /* I   Order */\n)\n{\n    SKP_int   i;\n    SKP_int32 tmp_32;\n    SKP_int32 one_div_diag_Q36, one_div_diag_Q48;\n\n    for( i = 0; i < M; i++ ) {\n        one_div_diag_Q36 = inv_D[ i ].Q36_part;\n        one_div_diag_Q48 = inv_D[ i ].Q48_part;\n\n        tmp_32 = T[ i ];\n        T[ i ] = SKP_ADD32( SKP_SMMUL( tmp_32, one_div_diag_Q48 ), SKP_RSHIFT( SKP_SMULWW( tmp_32, one_div_diag_Q36 ), 4 ) );\n    }\n}\n\n/* Solve Lx = b, when L is lower triangular and has ones on the diagonal */\nSKP_INLINE void SKP_Silk_LS_SolveFirst_FIX(\n    const SKP_int32     *L_Q16, /* I Pointer to Lower Triangular Matrix */\n    SKP_int             M,      /* I Dim of Matrix equation */\n    const SKP_int32     *b,     /* I b Vector */\n    SKP_int32           *x_Q16  /* O x Vector */  \n)\n{\n    SKP_int i, j;\n    const SKP_int32 *ptr32;\n    SKP_int32 tmp_32;\n\n    for( i = 0; i < M; i++ ) {\n        ptr32 = matrix_adr( L_Q16, i, 0, M );\n        tmp_32 = 0;\n        for( j = 0; j < i; j++ ) {\n            tmp_32 = SKP_SMLAWW( tmp_32, ptr32[ j ], x_Q16[ j ] );\n        }\n        x_Q16[ i ] = SKP_SUB32( b[ i ], tmp_32 );\n    }\n}\n\n/* Solve L^t*x = b, where L is lower triangular with ones on the diagonal */\nSKP_INLINE void SKP_Silk_LS_SolveLast_FIX(\n    const SKP_int32     *L_Q16,     /* I Pointer to Lower Triangular Matrix */\n    const SKP_int       M,          /* I Dim of Matrix equation */\n    const SKP_int32     *b,         /* I b Vector */\n    SKP_int32           *x_Q16      /* O x Vector */  \n)\n{\n    SKP_int i, j;\n    const SKP_int32 *ptr32;\n    SKP_int32 tmp_32;\n\n    for( i = M - 1; i >= 0; i-- ) {\n        ptr32 = matrix_adr( L_Q16, 0, i, M );\n        tmp_32 = 0;\n        for( j = M - 1; j > i; j-- ) {\n            tmp_32 = SKP_SMLAWW( tmp_32, ptr32[ SKP_SMULBB( j, M ) ], x_Q16[ j ] );\n        }\n        x_Q16[ i ] = SKP_SUB32( b[ i ], tmp_32 );\n    }\n}\n"
  },
  {
    "path": "app/jni/SKP_Silk_sort.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/* Insertion sort (fast for already almost sorted arrays):   */\n/* Best case:  O(n)   for an already sorted array            */\n/* Worst case: O(n^2) for an inversely sorted array          */\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n\nvoid SKP_Silk_insertion_sort_increasing(\n    SKP_int32           *a,             /* I/O:  Unsorted / Sorted vector               */\n    SKP_int             *index,         /* O:    Index vector for the sorted elements   */\n    const SKP_int       L,              /* I:    Vector length                          */\n    const SKP_int       K               /* I:    Number of correctly sorted output positions   */\n)\n{\n    SKP_int32    value;\n    SKP_int        i, j;\n\n    /* Safety checks */\n    SKP_assert( K >  0 );\n    SKP_assert( L >  0 );\n    SKP_assert( L >= K );\n\n    /* Write start indices in index vector */\n    for( i = 0; i < K; i++ ) {\n        index[ i ] = i;\n    }\n\n    /* Sort vector elements by value, increasing order */\n    for( i = 1; i < K; i++ ) {\n        value = a[ i ];\n        for( j = i - 1; ( j >= 0 ) && ( value < a[ j ] ); j-- ) {\n            a[ j + 1 ]     = a[ j ];     /* Shift value */\n            index[ j + 1 ] = index[ j ]; /* Shift index */\n        }\n        a[ j + 1 ]     = value; /* Write value */\n        index[ j + 1 ] = i;     /* Write index */\n    }\n\n    /* If less than L values are asked for, check the remaining values, */\n    /* but only spend CPU to ensure that the K first values are correct */\n    for( i = K; i < L; i++ ) {\n        value = a[ i ];\n        if( value < a[ K - 1 ] ) {\n            for( j = K - 2; ( j >= 0 ) && ( value < a[ j ] ); j-- ) {\n                a[ j + 1 ]     = a[ j ];     /* Shift value */\n                index[ j + 1 ] = index[ j ]; /* Shift index */\n            }\n            a[ j + 1 ]     = value; /* Write value */\n            index[ j + 1 ] = i;        /* Write index */\n        }\n    }\n}\n\nvoid SKP_Silk_insertion_sort_decreasing_int16(\n    SKP_int16           *a,             /* I/O: Unsorted / Sorted vector                */\n    SKP_int             *index,         /* O:   Index vector for the sorted elements    */\n    const SKP_int       L,              /* I:   Vector length                           */\n    const SKP_int       K               /* I:   Number of correctly sorted output positions    */\n)\n{\n    SKP_int i, j;\n    SKP_int value;\n\n    /* Safety checks */\n    SKP_assert( K >  0 );\n    SKP_assert( L >  0 );\n    SKP_assert( L >= K );\n\n    /* Write start indices in index vector */\n    for( i = 0; i < K; i++ ) {\n        index[ i ] = i;\n    }\n\n    /* Sort vector elements by value, decreasing order */\n    for( i = 1; i < K; i++ ) {\n        value = a[ i ];\n        for( j = i - 1; ( j >= 0 ) && ( value > a[ j ] ); j-- ) {    \n            a[ j + 1 ]     = a[ j ];     /* Shift value */\n            index[ j + 1 ] = index[ j ]; /* Shift index */\n        }\n        a[ j + 1 ]     = value; /* Write value */\n        index[ j + 1 ] = i;     /* Write index */\n    }\n\n    /* If less than L values are asked for, check the remaining values, */\n    /* but only spend CPU to ensure that the K first values are correct */\n    for( i = K; i < L; i++ ) {\n        value = a[ i ];\n        if( value > a[ K - 1 ] ) {\n            for( j = K - 2; ( j >= 0 ) && ( value > a[ j ] ); j-- ) {    \n                a[ j + 1 ]     = a[ j ];     /* Shift value */\n                index[ j + 1 ] = index[ j ]; /* Shift index */\n            }\n            a[ j + 1 ]     = value; /* Write value */\n            index[ j + 1 ] = i;     /* Write index */\n        }\n    }\n}\n\nvoid SKP_Silk_insertion_sort_increasing_all_values(\n    SKP_int             *a,             /* I/O: Unsorted / Sorted vector                */\n    const SKP_int       L               /* I:   Vector length                           */\n)\n{\n    SKP_int    value;\n    SKP_int    i, j;\n\n    /* Safety checks */\n    SKP_assert( L >  0 );\n\n    /* Sort vector elements by value, increasing order */\n    for( i = 1; i < L; i++ ) {\n        value = a[ i ];\n        for( j = i - 1; ( j >= 0 ) && ( value < a[ j ] ); j-- ) {\n            a[ j + 1 ] = a[ j ]; /* Shift value */\n        }\n        a[ j + 1 ] = value; /* Write value */\n    }\n}\n\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_sum_sqr_shift.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * SKP_Silk_sum_sqr_shift.c                                           *\n *                                                                      *\n * compute number of bits to right shift the sum of squares of a vector *\n * of int16s to make it fit in an int32                                 *\n *                                                                      *\n * Copyright 2006-2008 (c), Skype Limited                               *\n *                                                                      */\n#include \"SKP_Silk_SigProc_FIX.h\"\n#if (EMBEDDED_ARM<5) \n/* Compute number of bits to right shift the sum of squares of a vector */\n/* of int16s to make it fit in an int32                                 */\nvoid SKP_Silk_sum_sqr_shift(\n    SKP_int32            *energy,            /* O    Energy of x, after shifting to the right            */\n    SKP_int              *shift,             /* O    Number of bits right shift applied to energy        */\n    const SKP_int16      *x,                 /* I    Input vector                                        */\n    SKP_int              len                 /* I    Length of input vector                              */\n)\n{\n    SKP_int   i, shft;\n    SKP_int32 in32, nrg_tmp, nrg;\n\n    if( (SKP_int32)( (SKP_int_ptr_size)x & 2 ) != 0 ) {\n        /* Input is not 4-byte aligned */\n        nrg = SKP_SMULBB( x[ 0 ], x[ 0 ] );\n        i = 1;\n    } else {\n        nrg = 0;\n        i   = 0;\n    }\n    shft = 0;\n    len--;\n    while( i < len ) {\n        /* Load two values at once */\n        in32 = *( (SKP_int32 *)&x[ i ] );\n        nrg = SKP_SMLABB_ovflw( nrg, in32, in32 );\n        nrg = SKP_SMLATT_ovflw( nrg, in32, in32 );\n        i += 2;\n        if( nrg < 0 ) {\n            /* Scale down */\n            nrg = (SKP_int32)SKP_RSHIFT_uint( (SKP_uint32)nrg, 2 );\n            shft = 2;\n            break;\n        }\n    }\n    for( ; i < len; i += 2 ) {\n        /* Load two values at once */\n        in32 = *( (SKP_int32 *)&x[ i ] );\n        nrg_tmp = SKP_SMULBB( in32, in32 );\n        nrg_tmp = SKP_SMLATT_ovflw( nrg_tmp, in32, in32 );\n        nrg = (SKP_int32)SKP_ADD_RSHIFT_uint( nrg, (SKP_uint32)nrg_tmp, shft );\n        if( nrg < 0 ) {\n            /* Scale down */\n            nrg = (SKP_int32)SKP_RSHIFT_uint( (SKP_uint32)nrg, 2 );\n            shft += 2;\n        }\n    }\n    if( i == len ) {\n        /* One sample left to process */\n        nrg_tmp = SKP_SMULBB( x[ i ], x[ i ] );\n        nrg = (SKP_int32)SKP_ADD_RSHIFT_uint( nrg, nrg_tmp, shft );\n    }\n\n    /* Make sure to have at least one extra leading zero (two leading zeros in total) */\n    if( nrg & 0xC0000000 ) {\n        nrg = SKP_RSHIFT_uint( (SKP_uint32)nrg, 2 );\n        shft += 2;\n    }\n\n    /* Output arguments */\n    *shift  = shft;\n    *energy = nrg;\n}\n\n#endif\n"
  },
  {
    "path": "app/jni/SKP_Silk_tables_LTP.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_tables.h\"\n\nconst SKP_uint16 SKP_Silk_LTP_per_index_CDF[ 4 ] = {\n         0,  20992,  40788,  65535\n};\n\nconst SKP_int SKP_Silk_LTP_per_index_CDF_offset = 1;\n\n\nconst SKP_uint16 SKP_Silk_LTP_gain_CDF_0[ 11 ] = {\n         0,  49380,  54463,  56494,  58437,  60101,  61683,  62985,\n     64066,  64823,  65535\n};\n\nconst SKP_uint16 SKP_Silk_LTP_gain_CDF_1[ 21 ] = {\n         0,  25290,  30654,  35710,  40386,  42937,  45250,  47459,\n     49411,  51348,  52974,  54517,  55976,  57423,  58865,  60285,\n     61667,  62895,  63827,  64724,  65535\n};\n\nconst SKP_uint16 SKP_Silk_LTP_gain_CDF_2[ 41 ] = {\n         0,   4958,   9439,  13581,  17638,  21651,  25015,  28025,\n     30287,  32406,  34330,  36240,  38130,  39790,  41281,  42764,\n     44229,  45676,  47081,  48431,  49675,  50849,  51932,  52966,\n     53957,  54936,  55869,  56789,  57708,  58504,  59285,  60043,\n     60796,  61542,  62218,  62871,  63483,  64076,  64583,  65062,\n     65535\n};\n\nconst SKP_int SKP_Silk_LTP_gain_CDF_offsets[ 3 ] = {\n         1,     3,     10\n};\n\nconst SKP_int32 SKP_Silk_LTP_gain_middle_avg_RD_Q14 = 11010;\n\nconst SKP_int16 SKP_Silk_LTP_gain_BITS_Q6_0[ 10 ] = {\n        26,    236,    321,    325,    339,    344,    362,    379,\n       412,    418\n};\n\nconst SKP_int16 SKP_Silk_LTP_gain_BITS_Q6_1[ 20 ] = {\n        88,    231,    237,    244,    300,    309,    313,    324,\n       325,    341,    346,    351,    352,    352,    354,    356,\n       367,    393,    396,    406\n};\n\nconst SKP_int16 SKP_Silk_LTP_gain_BITS_Q6_2[ 40 ] = {\n       238,    248,    255,    257,    258,    274,    284,    311,\n       317,    326,    326,    327,    339,    349,    350,    351,\n       352,    355,    358,    366,    371,    379,    383,    387,\n       388,    393,    394,    394,    407,    409,    412,    412,\n       413,    422,    426,    432,    434,    449,    454,    455\n};\n\nconst SKP_uint16 * const SKP_Silk_LTP_gain_CDF_ptrs[ NB_LTP_CBKS ] = {\n    SKP_Silk_LTP_gain_CDF_0,\n    SKP_Silk_LTP_gain_CDF_1,\n    SKP_Silk_LTP_gain_CDF_2\n};\n\nconst SKP_int16 * const SKP_Silk_LTP_gain_BITS_Q6_ptrs[ NB_LTP_CBKS ] = {\n    SKP_Silk_LTP_gain_BITS_Q6_0,\n    SKP_Silk_LTP_gain_BITS_Q6_1,\n    SKP_Silk_LTP_gain_BITS_Q6_2\n};\n\nconst SKP_int16 SKP_Silk_LTP_gain_vq_0_Q14[ 10 ][ 5 ] = \n{\n{\n       594,    984,   2840,   1021,    669\n},\n{\n        10,     35,    304,     -1,     23\n},\n{\n      -694,   1923,   4603,   2975,   2335\n},\n{\n      2437,   3176,   3778,   1940,    481\n},\n{\n       214,    -46,   7870,   4406,   -521\n},\n{\n      -896,   4818,   8501,   1623,   -887\n},\n{\n      -696,   3178,   6480,   -302,   1081\n},\n{\n       517,    599,   1002,    567,    560\n},\n{\n     -2075,   -834,   4712,   -340,    896\n},\n{\n      1435,   -644,   3993,   -612,  -2063\n}\n};\n\nconst SKP_int16 SKP_Silk_LTP_gain_vq_1_Q14[ 20 ][ 5 ] = \n{\n{\n      1655,   2918,   5001,   3010,   1775\n},\n{\n       113,    198,    856,    176,    178\n},\n{\n      -843,   2479,   7858,   5371,    574\n},\n{\n        59,   5356,   7648,   2850,   -315\n},\n{\n      3840,   4851,   6527,   1583,  -1233\n},\n{\n      1620,   1760,   2330,   1876,   2045\n},\n{\n      -545,   1854,  11792,   1547,   -307\n},\n{\n      -604,    689,   5369,   5074,   4265\n},\n{\n       521,  -1331,   9829,   6209,  -1211\n},\n{\n     -1315,   6747,   9929,  -1410,    546\n},\n{\n       117,   -144,   2810,   1649,   5240\n},\n{\n      5392,   3476,   2425,    -38,    633\n},\n{\n        14,   -449,   5274,   3547,   -171\n},\n{\n       -98,    395,   9114,   1676,    844\n},\n{\n      -908,   3843,   8861,   -957,   1474\n},\n{\n       396,   6747,   5379,   -329,   1269\n},\n{\n      -335,   2830,   4281,    270,    -54\n},\n{\n      1502,   5609,   8958,   6045,   2059\n},\n{\n      -370,    479,   5267,   5726,   1174\n},\n{\n      5237,  -1144,   6510,    455,    512\n}\n};\n\nconst SKP_int16 SKP_Silk_LTP_gain_vq_2_Q14[ 40 ][ 5 ] = \n{\n{\n      -278,    415,   9345,   7106,   -431\n},\n{\n     -1006,   3863,   9524,   4724,   -871\n},\n{\n      -954,   4624,  11722,    973,   -300\n},\n{\n      -117,   7066,   8331,   1959,   -901\n},\n{\n       593,   3412,   6070,   4914,   1567\n},\n{\n        54,    -51,  12618,   4228,   -844\n},\n{\n      3157,   4822,   5229,   2313,    717\n},\n{\n      -244,   1161,  14198,    779,     69\n},\n{\n     -1218,   5603,  12894,  -2301,   1001\n},\n{\n      -132,   3960,   9526,    577,   1806\n},\n{\n     -1633,   8815,  10484,  -2452,    895\n},\n{\n       235,    450,   1243,    667,    437\n},\n{\n       959,  -2630,  10897,   8772,  -1852\n},\n{\n      2420,   2046,   8893,   4427,  -1569\n},\n{\n        23,   7091,   8356,  -1285,   1508\n},\n{\n     -1133,    835,   7662,   6043,   2800\n},\n{\n       439,    391,  11016,   2253,   1362\n},\n{\n     -1020,   2876,  13436,   4015,  -3020\n},\n{\n      1060,  -2690,  13512,   5565,  -1394\n},\n{\n     -1420,   8007,  11421,   -152,  -1672\n},\n{\n      -893,   2895,  15434,  -1490,    159\n},\n{\n     -1054,    428,  12208,   8538,  -3344\n},\n{\n      1772,  -1304,   7593,   6185,    561\n},\n{\n       525,  -1207,   6659,  11151,  -1170\n},\n{\n       439,   2667,   4743,   2359,   5515\n},\n{\n      2951,   7432,   7909,   -230,  -1564\n},\n{\n       -72,   2140,   5477,   1391,   1580\n},\n{\n       476,  -1312,  15912,   2174,  -1027\n},\n{\n      5737,    441,   2493,   2043,   2757\n},\n{\n       228,    -43,   1803,   6663,   7064\n},\n{\n      4596,   9182,   1917,   -200,    203\n},\n{\n      -704,  12039,   5451,  -1188,    542\n},\n{\n      1782,  -1040,  10078,   7513,  -2767\n},\n{\n     -2626,   7747,   9019,     62,   1710\n},\n{\n       235,   -233,   2954,  10921,   1947\n},\n{\n     10854,   2814,   1232,   -111,    222\n},\n{\n      2267,   2778,  12325,    156,  -1658\n},\n{\n     -2950,   8095,  16330,    268,  -3626\n},\n{\n        67,   2083,   7950,    -80,  -2432\n},\n{\n       518,    -66,   1718,    415,  11435\n}\n};\n\nconst SKP_int16 * const SKP_Silk_LTP_vq_ptrs_Q14[ NB_LTP_CBKS ] = {\n    &SKP_Silk_LTP_gain_vq_0_Q14[ 0 ][ 0 ],\n    &SKP_Silk_LTP_gain_vq_1_Q14[ 0 ][ 0 ],\n    &SKP_Silk_LTP_gain_vq_2_Q14[ 0 ][ 0 ]\n};\n \nconst SKP_int SKP_Silk_LTP_vq_sizes[ NB_LTP_CBKS ] = {\n    10, 20, 40 \n};\n"
  },
  {
    "path": "app/jni/SKP_Silk_tables_NLSF_CB0_10.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/**********************************************/\n/* This file has been automatically generated */\n/*                                            */\n/* ROM usage:  0.29 + 2.66 kB                 */\n/**********************************************/\n\n#include \"SKP_Silk_structs.h\"\n#include \"SKP_Silk_tables_NLSF_CB0_10.h\"\n#include \"SKP_Silk_tables.h\"\n\nconst SKP_uint16 SKP_Silk_NLSF_MSVQ_CB0_10_CDF[ NLSF_MSVQ_CB0_10_VECTORS + NLSF_MSVQ_CB0_10_STAGES ] =\n{\n            0,\n         2658,\n         4420,\n         6107,\n         7757,\n         9408,\n        10955,\n        12502,\n        13983,\n        15432,\n        16882,\n        18331,\n        19750,\n        21108,\n        22409,\n        23709,\n        25010,\n        26256,\n        27501,\n        28747,\n        29965,\n        31158,\n        32351,\n        33544,\n        34736,\n        35904,\n        36997,\n        38091,\n        39185,\n        40232,\n        41280,\n        42327,\n        43308,\n        44290,\n        45271,\n        46232,\n        47192,\n        48132,\n        49032,\n        49913,\n        50775,\n        51618,\n        52462,\n        53287,\n        54095,\n        54885,\n        55675,\n        56449,\n        57222,\n        57979,\n        58688,\n        59382,\n        60076,\n        60726,\n        61363,\n        61946,\n        62505,\n        63052,\n        63543,\n        63983,\n        64396,\n        64766,\n        65023,\n        65279,\n        65535,\n            0,\n         4977,\n         9542,\n        14106,\n        18671,\n        23041,\n        27319,\n        31596,\n        35873,\n        39969,\n        43891,\n        47813,\n        51652,\n        55490,\n        59009,\n        62307,\n        65535,\n            0,\n         8571,\n        17142,\n        25529,\n        33917,\n        42124,\n        49984,\n        57844,\n        65535,\n            0,\n         8732,\n        17463,\n        25825,\n        34007,\n        42189,\n        50196,\n        58032,\n        65535,\n            0,\n         8948,\n        17704,\n        25733,\n        33762,\n        41791,\n        49821,\n        57678,\n        65535,\n            0,\n         4374,\n         8655,\n        12936,\n        17125,\n        21313,\n        25413,\n        29512,\n        33611,\n        37710,\n        41809,\n        45820,\n        49832,\n        53843,\n        57768,\n        61694,\n        65535\n};\n\nconst SKP_uint16 * const SKP_Silk_NLSF_MSVQ_CB0_10_CDF_start_ptr[ NLSF_MSVQ_CB0_10_STAGES ] =\n{\n     &SKP_Silk_NLSF_MSVQ_CB0_10_CDF[   0 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_10_CDF[  65 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_10_CDF[  82 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_10_CDF[  91 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_10_CDF[ 100 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_10_CDF[ 109 ]\n};\n\nconst SKP_int SKP_Silk_NLSF_MSVQ_CB0_10_CDF_middle_idx[ NLSF_MSVQ_CB0_10_STAGES ] =\n{\n      23,\n       8,\n       5,\n       5,\n       5,\n       9\n};\n\nconst SKP_int16 SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[ NLSF_MSVQ_CB0_10_VECTORS ] =\n{\n              148,              167,\n              169,              170,\n              170,              173,\n              173,              175,\n              176,              176,\n              176,              177,\n              179,              181,\n              181,              181,\n              183,              183,\n              183,              184,\n              185,              185,\n              185,              185,\n              186,              189,\n              189,              189,\n              191,              191,\n              191,              194,\n              194,              194,\n              195,              195,\n              196,              198,\n              199,              200,\n              201,              201,\n              202,              203,\n              204,              204,\n              205,              205,\n              206,              209,\n              210,              210,\n              213,              214,\n              218,              220,\n              221,              226,\n              231,              234,\n              239,              256,\n              256,              256,\n              119,              123,\n              123,              123,\n              125,              126,\n              126,              126,\n              128,              130,\n              130,              131,\n              131,              135,\n              138,              139,\n               94,               94,\n               95,               95,\n               96,               98,\n               98,               99,\n               93,               93,\n               95,               96,\n               96,               97,\n               98,              100,\n               92,               93,\n               97,               97,\n               97,               97,\n               98,               98,\n              125,              126,\n              126,              127,\n              127,              128,\n              128,              128,\n              128,              128,\n              129,              129,\n              129,              130,\n              130,              131\n};\n\nconst SKP_int SKP_Silk_NLSF_MSVQ_CB0_10_ndelta_min_Q15[ 10 + 1 ] =\n{\n              563,\n                3,\n               22,\n               20,\n                3,\n                3,\n              132,\n              119,\n              358,\n               86,\n              964\n};\n\nconst SKP_int16 SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 * NLSF_MSVQ_CB0_10_VECTORS ] =\n{\n             2210,             4023,\n             6981,             9260,\n            12573,            15687,\n            19207,            22383,\n            25981,            29142,\n             3285,             4172,\n             6116,            10856,\n            15289,            16826,\n            19701,            22010,\n            24721,            29313,\n             1554,             2511,\n             6577,            10337,\n            13837,            16511,\n            20086,            23214,\n            26480,            29464,\n             3062,             4017,\n             5771,            10037,\n            13365,            14952,\n            20140,            22891,\n            25229,            29603,\n             2085,             3457,\n             5934,             8718,\n            11501,            13670,\n            17997,            21817,\n            24935,            28745,\n             2776,             4093,\n             6421,            10413,\n            15111,            16806,\n            20825,            23826,\n            26308,            29411,\n             2717,             4034,\n             5697,             8463,\n            14301,            16354,\n            19007,            23413,\n            25812,            28506,\n             2872,             3702,\n             5881,            11034,\n            17141,            18879,\n            21146,            23451,\n            25817,            29600,\n             2999,             4015,\n             7357,            11219,\n            12866,            17307,\n            20081,            22644,\n            26774,            29107,\n             2942,             3866,\n             5918,            11915,\n            13909,            16072,\n            20453,            22279,\n            27310,            29826,\n             2271,             3527,\n             6606,             9729,\n            12943,            17382,\n            20224,            22345,\n            24602,            28290,\n             2207,             3310,\n             5844,             9339,\n            11141,            15651,\n            18576,            21177,\n            25551,            28228,\n             3963,             4975,\n             6901,            11588,\n            13466,            15577,\n            19231,            21368,\n            25510,            27759,\n             2749,             3549,\n             6966,            13808,\n            15653,            17645,\n            20090,            22599,\n            26467,            28537,\n             2126,             3504,\n             5109,             9954,\n            12550,            14620,\n            19703,            21687,\n            26457,            29106,\n             3966,             5745,\n             7442,             9757,\n            14468,            16404,\n            19135,            23048,\n            25375,            28391,\n             3197,             4751,\n             6451,             9298,\n            13038,            14874,\n            17962,            20627,\n            23835,            28464,\n             3195,             4081,\n             6499,            12252,\n            14289,            16040,\n            18357,            20730,\n            26980,            29309,\n             1533,             2471,\n             4486,             7796,\n            12332,            15758,\n            19567,            22298,\n            25673,            29051,\n             2002,             2971,\n             4985,             8083,\n            13181,            15435,\n            18237,            21517,\n            24595,            28351,\n             3808,             4925,\n             6710,            10201,\n            12011,            14300,\n            18457,            20391,\n            26525,            28956,\n             2281,             3418,\n             4979,             8726,\n            15964,            18104,\n            20250,            22771,\n            25286,            28954,\n             3051,             5479,\n             7290,             9848,\n            12744,            14503,\n            18665,            23684,\n            26065,            28947,\n             2364,             3565,\n             5502,             9621,\n            14922,            16621,\n            19005,            20996,\n            26310,            29302,\n             4093,             5212,\n             6833,             9880,\n            16303,            18286,\n            20571,            23614,\n            26067,            29128,\n             2941,             3996,\n             6038,            10638,\n            12668,            14451,\n            16798,            19392,\n            26051,            28517,\n             3863,             5212,\n             7019,             9468,\n            11039,            13214,\n            19942,            22344,\n            25126,            29539,\n             4615,             6172,\n             7853,            10252,\n            12611,            14445,\n            19719,            22441,\n            24922,            29341,\n             3566,             4512,\n             6985,             8684,\n            10544,            16097,\n            18058,            22475,\n            26066,            28167,\n             4481,             5489,\n             7432,            11414,\n            13191,            15225,\n            20161,            22258,\n            26484,            29716,\n             3320,             4320,\n             6621,             9867,\n            11581,            14034,\n            21168,            23210,\n            26588,            29903,\n             3794,             4689,\n             6916,             8655,\n            10143,            16144,\n            19568,            21588,\n            27557,            29593,\n             2446,             3276,\n             5918,            12643,\n            16601,            18013,\n            21126,            23175,\n            27300,            29634,\n             2450,             3522,\n             5437,             8560,\n            15285,            19911,\n            21826,            24097,\n            26567,            29078,\n             2580,             3796,\n             5580,             8338,\n             9969,            12675,\n            18907,            22753,\n            25450,            29292,\n             3325,             4312,\n             6241,             7709,\n             9164,            14452,\n            21665,            23797,\n            27096,            29857,\n             3338,             4163,\n             7738,            11114,\n            12668,            14753,\n            16931,            22736,\n            25671,            28093,\n             3840,             4755,\n             7755,            13471,\n            15338,            17180,\n            20077,            22353,\n            27181,            29743,\n             2504,             4079,\n             8351,            12118,\n            15046,            18595,\n            21684,            24704,\n            27519,            29937,\n             5234,             6342,\n             8267,            11821,\n            15155,            16760,\n            20667,            23488,\n            25949,            29307,\n             2681,             3562,\n             6028,            10827,\n            18458,            20458,\n            22303,            24701,\n            26912,            29956,\n             3374,             4528,\n             6230,             8256,\n             9513,            12730,\n            18666,            20720,\n            26007,            28425,\n             2731,             3629,\n             8320,            12450,\n            14112,            16431,\n            18548,            22098,\n            25329,            27718,\n             3481,             4401,\n             7321,             9319,\n            11062,            13093,\n            15121,            22315,\n            26331,            28740,\n             3577,             4945,\n             6669,             8792,\n            10299,            12645,\n            19505,            24766,\n            26996,            29634,\n             4058,             5060,\n             7288,            10190,\n            11724,            13936,\n            15849,            18539,\n            26701,            29845,\n             4262,             5390,\n             7057,             8982,\n            10187,            15264,\n            20480,            22340,\n            25958,            28072,\n             3404,             4329,\n             6629,             7946,\n            10121,            17165,\n            19640,            22244,\n            25062,            27472,\n             3157,             4168,\n             6195,             9319,\n            10771,            13325,\n            15416,            19816,\n            24672,            27634,\n             2503,             3473,\n             5130,             6767,\n             8571,            14902,\n            19033,            21926,\n            26065,            28728,\n             4133,             5102,\n             7553,            10054,\n            11757,            14924,\n            17435,            20186,\n            23987,            26272,\n             4972,             6139,\n             7894,             9633,\n            11320,            14295,\n            21737,            24306,\n            26919,            29907,\n             2958,             3816,\n             6851,             9204,\n            10895,            18052,\n            20791,            23338,\n            27556,            29609,\n             5234,             6028,\n             8034,            10154,\n            11242,            14789,\n            18948,            20966,\n            26585,            29127,\n             5241,             6838,\n            10526,            12819,\n            14681,            17328,\n            19928,            22336,\n            26193,            28697,\n             3412,             4251,\n             5988,             7094,\n             9907,            18243,\n            21669,            23777,\n            26969,            29087,\n             2470,             3217,\n             7797,            15296,\n            17365,            19135,\n            21979,            24256,\n            27322,            29442,\n             4939,             5804,\n             8145,            11809,\n            13873,            15598,\n            17234,            19423,\n            26476,            29645,\n             5051,             6167,\n             8223,             9655,\n            12159,            17995,\n            20464,            22832,\n            26616,            28462,\n             4987,             5907,\n             9319,            11245,\n            13132,            15024,\n            17485,            22687,\n            26011,            28273,\n             5137,             6884,\n            11025,            14950,\n            17191,            19425,\n            21807,            24393,\n            26938,            29288,\n             7057,             7884,\n             9528,            10483,\n            10960,            14811,\n            19070,            21675,\n            25645,            28019,\n             6759,             7160,\n             8546,            11779,\n            12295,            13023,\n            16627,            21099,\n            24697,            28287,\n             3863,             9762,\n            11068,            11445,\n            12049,            13960,\n            18085,            21507,\n            25224,            28997,\n              397,              335,\n              651,             1168,\n              640,              765,\n              465,              331,\n              214,             -194,\n             -578,             -647,\n             -657,              750,\n              564,              613,\n              549,              630,\n              304,              -52,\n              828,              922,\n              443,              111,\n              138,              124,\n              169,               14,\n              144,               83,\n              132,               58,\n             -413,             -752,\n              869,              336,\n              385,               69,\n               56,              830,\n             -227,             -266,\n             -368,             -440,\n            -1195,              163,\n              126,             -228,\n              802,              156,\n              188,              120,\n              376,               59,\n             -358,             -558,\n            -1326,             -254,\n             -202,             -789,\n              296,               92,\n              -70,             -129,\n             -718,            -1135,\n              292,              -29,\n             -631,              487,\n             -157,             -153,\n             -279,                2,\n             -419,             -342,\n              -34,             -514,\n             -799,            -1571,\n             -687,             -609,\n             -546,             -130,\n             -215,             -252,\n             -446,             -574,\n            -1337,              207,\n              -72,               32,\n              103,             -642,\n              942,              733,\n              187,               29,\n             -211,             -814,\n              143,              225,\n               20,               24,\n             -268,             -377,\n             1623,             1133,\n              667,              164,\n              307,              366,\n              187,               34,\n               62,             -313,\n             -832,            -1482,\n            -1181,              483,\n              -42,              -39,\n             -450,            -1406,\n             -587,              -52,\n             -760,              334,\n               98,              -60,\n             -500,             -488,\n            -1058,              299,\n              131,             -250,\n             -251,             -703,\n             1037,              568,\n             -413,             -265,\n             1687,              573,\n              345,              323,\n               98,               61,\n             -102,               31,\n              135,              149,\n              617,              365,\n              -39,               34,\n             -611,             1201,\n             1421,              736,\n             -414,             -393,\n             -492,             -343,\n             -316,             -532,\n              528,              172,\n               90,              322,\n             -294,             -319,\n             -541,              503,\n              639,              401,\n                1,             -149,\n              -73,             -167,\n              150,              118,\n              308,              218,\n              121,              195,\n             -143,             -261,\n            -1013,             -802,\n              387,              436,\n              130,             -427,\n             -448,             -681,\n              123,              -87,\n             -251,             -113,\n              274,              310,\n              445,              501,\n              354,              272,\n              141,             -285,\n              569,              656,\n               37,              -49,\n              251,             -386,\n             -263,             1122,\n              604,              606,\n              336,               95,\n               34,                0,\n               85,              180,\n              207,             -367,\n             -622,             1070,\n               -6,              -79,\n             -160,              -92,\n             -137,             -276,\n             -323,             -371,\n             -696,            -1036,\n              407,              102,\n              -86,             -214,\n             -482,             -647,\n              -28,             -291,\n              -97,             -180,\n             -250,             -435,\n              -18,              -76,\n             -332,              410,\n              407,              168,\n              539,              411,\n              254,              111,\n               58,             -145,\n              200,               30,\n              187,              116,\n              131,             -367,\n             -475,              781,\n             -559,              561,\n              195,             -115,\n                8,             -168,\n               30,               55,\n             -122,              131,\n               82,               -5,\n             -273,              -50,\n             -632,              668,\n                4,               32,\n              -26,             -279,\n              315,              165,\n              197,              377,\n              155,              -41,\n             -138,             -324,\n             -109,             -617,\n              360,               98,\n              -53,             -319,\n             -114,             -245,\n              -82,              507,\n              468,              263,\n             -137,             -389,\n              652,              354,\n              -18,             -227,\n             -462,             -135,\n              317,               53,\n              -16,               66,\n              -72,             -126,\n             -356,             -347,\n             -328,              -72,\n             -337,              324,\n              152,              349,\n              169,             -196,\n              179,              254,\n              260,              325,\n              -74,              -80,\n               75,              -31,\n              270,              275,\n               87,              278,\n             -446,             -301,\n              309,               71,\n              -25,             -242,\n              516,              161,\n             -162,              -83,\n              329,              230,\n             -311,             -259,\n              177,              -26,\n             -462,               89,\n              257,                6,\n             -130,              -93,\n             -456,             -317,\n             -221,             -206,\n             -417,             -182,\n              -74,              234,\n               48,              261,\n              359,              231,\n              258,               85,\n             -282,              252,\n             -147,             -222,\n              251,             -207,\n              443,              123,\n             -417,              -36,\n              273,             -241,\n              240,             -112,\n               44,             -167,\n              126,             -124,\n              -77,               58,\n             -401,              333,\n             -118,               82,\n              126,              151,\n             -433,              359,\n             -130,             -102,\n              131,             -244,\n               86,               85,\n             -462,              414,\n             -240,               16,\n              145,               28,\n             -205,             -481,\n              373,              293,\n              -72,             -174,\n               62,              259,\n               -8,              -18,\n              362,              233,\n              185,               43,\n              278,               27,\n              193,              570,\n             -248,              189,\n               92,               31,\n             -275,               -3,\n              243,              176,\n              438,              209,\n              206,              -51,\n               79,              109,\n              168,             -185,\n             -308,              -68,\n             -618,              385,\n             -310,             -108,\n             -164,              165,\n               61,             -152,\n             -101,             -412,\n             -268,             -257,\n              -40,              -20,\n              -28,             -158,\n             -301,              271,\n              380,             -338,\n             -367,             -132,\n               64,              114,\n             -131,             -225,\n             -156,             -260,\n              -63,             -116,\n              155,             -586,\n             -202,              254,\n             -287,              178,\n              227,             -106,\n             -294,              164,\n              298,             -100,\n              185,              317,\n              193,              -45,\n               28,               80,\n              -87,             -433,\n               22,              -48,\n               48,             -237,\n             -229,             -139,\n              120,             -364,\n              268,             -136,\n              396,              125,\n              130,              -89,\n             -272,              118,\n             -256,              -68,\n             -451,              488,\n              143,             -165,\n              -48,             -190,\n              106,              219,\n               47,              435,\n              245,               97,\n               75,             -418,\n              121,             -187,\n              570,             -200,\n             -351,              225,\n              -21,             -217,\n              234,             -111,\n              194,               14,\n              242,              118,\n              140,             -397,\n              355,              361,\n              -45,             -195\n};\n\nconst SKP_Silk_NLSF_CBS SKP_Silk_NLSF_CB0_10_Stage_info[ NLSF_MSVQ_CB0_10_STAGES ] =\n{\n        {  64, &SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 *   0 ], &SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[   0 ] },\n        {  16, &SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 *  64 ], &SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[  64 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 *  80 ], &SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[  80 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 *  88 ], &SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[  88 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 *  96 ], &SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[  96 ] },\n        {  16, &SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 * 104 ], &SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[ 104 ] }\n};\n\nconst SKP_Silk_NLSF_CB_struct SKP_Silk_NLSF_CB0_10 =\n{\n        NLSF_MSVQ_CB0_10_STAGES,\n        SKP_Silk_NLSF_CB0_10_Stage_info,\n        SKP_Silk_NLSF_MSVQ_CB0_10_ndelta_min_Q15,\n        SKP_Silk_NLSF_MSVQ_CB0_10_CDF,\n        SKP_Silk_NLSF_MSVQ_CB0_10_CDF_start_ptr,\n        SKP_Silk_NLSF_MSVQ_CB0_10_CDF_middle_idx\n};\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_tables_NLSF_CB0_16.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/**********************************************/\n/* This file has been automatically generated */\n/*                                            */\n/* ROM usage:  0.51 + 7.38 kB                 */\n/**********************************************/\n\n#include \"SKP_Silk_structs.h\"\n#include \"SKP_Silk_tables_NLSF_CB0_16.h\"\n#include \"SKP_Silk_tables.h\"\n\nconst SKP_uint16 SKP_Silk_NLSF_MSVQ_CB0_16_CDF[ NLSF_MSVQ_CB0_16_VECTORS + NLSF_MSVQ_CB0_16_STAGES ] =\n{\n            0,\n         1449,\n         2749,\n         4022,\n         5267,\n         6434,\n         7600,\n         8647,\n         9695,\n        10742,\n        11681,\n        12601,\n        13444,\n        14251,\n        15008,\n        15764,\n        16521,\n        17261,\n        18002,\n        18710,\n        19419,\n        20128,\n        20837,\n        21531,\n        22225,\n        22919,\n        23598,\n        24277,\n        24956,\n        25620,\n        26256,\n        26865,\n        27475,\n        28071,\n        28667,\n        29263,\n        29859,\n        30443,\n        31026,\n        31597,\n        32168,\n        32727,\n        33273,\n        33808,\n        34332,\n        34855,\n        35379,\n        35902,\n        36415,\n        36927,\n        37439,\n        37941,\n        38442,\n        38932,\n        39423,\n        39914,\n        40404,\n        40884,\n        41364,\n        41844,\n        42324,\n        42805,\n        43285,\n        43754,\n        44224,\n        44694,\n        45164,\n        45623,\n        46083,\n        46543,\n        46993,\n        47443,\n        47892,\n        48333,\n        48773,\n        49213,\n        49653,\n        50084,\n        50515,\n        50946,\n        51377,\n        51798,\n        52211,\n        52614,\n        53018,\n        53422,\n        53817,\n        54212,\n        54607,\n        55002,\n        55388,\n        55775,\n        56162,\n        56548,\n        56910,\n        57273,\n        57635,\n        57997,\n        58352,\n        58698,\n        59038,\n        59370,\n        59702,\n        60014,\n        60325,\n        60630,\n        60934,\n        61239,\n        61537,\n        61822,\n        62084,\n        62346,\n        62602,\n        62837,\n        63072,\n        63302,\n        63517,\n        63732,\n        63939,\n        64145,\n        64342,\n        64528,\n        64701,\n        64867,\n        65023,\n        65151,\n        65279,\n        65407,\n        65535,\n            0,\n         5099,\n         9982,\n        14760,\n        19538,\n        24213,\n        28595,\n        32976,\n        36994,\n        41012,\n        44944,\n        48791,\n        52557,\n        56009,\n        59388,\n        62694,\n        65535,\n            0,\n         9955,\n        19697,\n        28825,\n        36842,\n        44686,\n        52198,\n        58939,\n        65535,\n            0,\n         8949,\n        17335,\n        25720,\n        33926,\n        41957,\n        49987,\n        57845,\n        65535,\n            0,\n         9724,\n        18642,\n        26998,\n        35355,\n        43532,\n        51534,\n        59365,\n        65535,\n            0,\n         8750,\n        17499,\n        26249,\n        34448,\n        42471,\n        50494,\n        58178,\n        65535,\n            0,\n         8730,\n        17273,\n        25816,\n        34176,\n        42536,\n        50203,\n        57869,\n        65535,\n            0,\n         8769,\n        17538,\n        26307,\n        34525,\n        42742,\n        50784,\n        58319,\n        65535,\n            0,\n         8736,\n        17101,\n        25466,\n        33653,\n        41839,\n        50025,\n        57864,\n        65535,\n            0,\n         4368,\n         8735,\n        12918,\n        17100,\n        21283,\n        25465,\n        29558,\n        33651,\n        37744,\n        41836,\n        45929,\n        50022,\n        54027,\n        57947,\n        61782,\n        65535\n};\n\nconst SKP_uint16 * const SKP_Silk_NLSF_MSVQ_CB0_16_CDF_start_ptr[ NLSF_MSVQ_CB0_16_STAGES ] =\n{\n     &SKP_Silk_NLSF_MSVQ_CB0_16_CDF[   0 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_16_CDF[ 129 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_16_CDF[ 146 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_16_CDF[ 155 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_16_CDF[ 164 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_16_CDF[ 173 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_16_CDF[ 182 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_16_CDF[ 191 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_16_CDF[ 200 ],\n     &SKP_Silk_NLSF_MSVQ_CB0_16_CDF[ 209 ]\n};\n\nconst SKP_int SKP_Silk_NLSF_MSVQ_CB0_16_CDF_middle_idx[ NLSF_MSVQ_CB0_16_STAGES ] =\n{\n      42,\n       8,\n       4,\n       5,\n       5,\n       5,\n       5,\n       5,\n       5,\n       9\n};\n\nconst SKP_int16 SKP_Silk_NLSF_MSVQ_CB0_16_rates_Q5[ NLSF_MSVQ_CB0_16_VECTORS ] =\n{\n              176,              181,\n              182,              183,\n              186,              186,\n              191,              191,\n              191,              196,\n              197,              201,\n              203,              206,\n              206,              206,\n              207,              207,\n              209,              209,\n              209,              209,\n              210,              210,\n              210,              211,\n              211,              211,\n              212,              214,\n              216,              216,\n              217,              217,\n              217,              217,\n              218,              218,\n              219,              219,\n              220,              221,\n              222,              223,\n              223,              223,\n              223,              224,\n              224,              224,\n              225,              225,\n              226,              226,\n              226,              226,\n              227,              227,\n              227,              227,\n              227,              227,\n              228,              228,\n              228,              228,\n              229,              229,\n              229,              230,\n              230,              230,\n              231,              231,\n              231,              231,\n              232,              232,\n              232,              232,\n              233,              234,\n              235,              235,\n              235,              236,\n              236,              236,\n              236,              237,\n              237,              237,\n              237,              240,\n              240,              240,\n              240,              241,\n              242,              243,\n              244,              244,\n              247,              247,\n              248,              248,\n              248,              249,\n              251,              255,\n              255,              256,\n              260,              260,\n              261,              264,\n              264,              266,\n              266,              268,\n              271,              274,\n              276,              279,\n              288,              288,\n              288,              288,\n              118,              120,\n              121,              121,\n              122,              125,\n              125,              129,\n              129,              130,\n              131,              132,\n              136,              137,\n              138,              145,\n               87,               88,\n               91,               97,\n               98,              100,\n              105,              106,\n               92,               95,\n               95,               96,\n               97,               97,\n               98,               99,\n               88,               92,\n               95,               95,\n               96,               97,\n               98,              109,\n               93,               93,\n               93,               96,\n               97,               97,\n               99,              101,\n               93,               94,\n               94,               95,\n               95,               99,\n               99,               99,\n               93,               93,\n               93,               96,\n               96,               97,\n              100,              102,\n               93,               95,\n               95,               96,\n               96,               96,\n               98,               99,\n              125,              125,\n              127,              127,\n              127,              127,\n              128,              128,\n              128,              128,\n              128,              128,\n              129,              130,\n              131,              132\n};\n\nconst SKP_int SKP_Silk_NLSF_MSVQ_CB0_16_ndelta_min_Q15[ 16 + 1 ] =\n{\n              266,\n                3,\n               40,\n                3,\n                3,\n               16,\n               78,\n               89,\n              107,\n              141,\n              188,\n              146,\n              272,\n              240,\n              235,\n              215,\n              632\n};\n\nconst SKP_int16 SKP_Silk_NLSF_MSVQ_CB0_16_Q15[ 16 * NLSF_MSVQ_CB0_16_VECTORS ] =\n{\n             1170,             2278,             3658,             5374,\n             7666,             9113,            11298,            13304,\n            15371,            17549,            19587,            21487,\n            23798,            26038,            28318,            30201,\n             1628,             2334,             4115,             6036,\n             7818,             9544,            11777,            14021,\n            15787,            17408,            19466,            21261,\n            22886,            24565,            26714,            28059,\n             1724,             2670,             4056,             6532,\n             8357,            10119,            12093,            14061,\n            16491,            18795,            20417,            22402,\n            24251,            26224,            28410,            29956,\n             1493,             3427,             4789,             6399,\n             8435,            10168,            12000,            14066,\n            16229,            18210,            20040,            22098,\n            24153,            26095,            28183,            30121,\n             1119,             2089,             4295,             6245,\n             8691,            10741,            12688,            15057,\n            17028,            18792,            20717,            22514,\n            24497,            26548,            28619,            30630,\n             1363,             2417,             3927,             5556,\n             7422,             9315,            11879,            13767,\n            16143,            18520,            20458,            22578,\n            24539,            26436,            28318,            30318,\n             1122,             2503,             5216,             7148,\n             9310,            11078,            13175,            14800,\n            16864,            18700,            20436,            22488,\n            24572,            26602,            28555,            30426,\n              600,             1317,             2970,             5609,\n             7694,             9784,            12169,            14087,\n            16379,            18378,            20551,            22686,\n            24739,            26697,            28646,            30355,\n              941,             1882,             4274,             5540,\n             8482,             9858,            11940,            14287,\n            16091,            18501,            20326,            22612,\n            24711,            26638,            28814,            30430,\n              635,             1699,             4376,             5948,\n             8097,            10115,            12274,            14178,\n            16111,            17813,            19695,            21773,\n            23927,            25866,            28022,            30134,\n             1408,             2222,             3524,             5615,\n             7345,             8849,            10989,            12772,\n            15352,            17026,            18919,            21062,\n            23329,            25215,            27209,            29023,\n              701,             1307,             3548,             6301,\n             7744,             9574,            11227,            12978,\n            15170,            17565,            19775,            22097,\n            24230,            26335,            28377,            30231,\n             1752,             2364,             4879,             6569,\n             7813,             9796,            11199,            14290,\n            15795,            18000,            20396,            22417,\n            24308,            26124,            28360,            30633,\n              901,             1629,             3356,             4635,\n             7256,             8767,             9971,            11558,\n            15215,            17544,            19523,            21852,\n            23900,            25978,            28133,            30184,\n              981,             1669,             3323,             4693,\n             6213,             8692,            10614,            12956,\n            15211,            17711,            19856,            22122,\n            24344,            26592,            28723,            30481,\n             1607,             2577,             4220,             5512,\n             8532,            10388,            11627,            13671,\n            15752,            17199,            19840,            21859,\n            23494,            25786,            28091,            30131,\n              811,             1471,             3144,             5041,\n             7430,             9389,            11174,            13255,\n            15157,            16741,            19583,            22167,\n            24115,            26142,            28383,            30395,\n             1543,             2144,             3629,             6347,\n             7333,             9339,            10710,            13596,\n            15099,            17340,            20102,            21886,\n            23732,            25637,            27818,            29917,\n              492,             1185,             2940,             5488,\n             7095,             8751,            11596,            13579,\n            16045,            18015,            20178,            22127,\n            24265,            26406,            28484,            30357,\n             1547,             2282,             3693,             6341,\n             7758,             9607,            11848,            13236,\n            16564,            18069,            19759,            21404,\n            24110,            26606,            28786,            30655,\n              685,             1338,             3409,             5262,\n             6950,             9222,            11414,            14523,\n            16337,            17893,            19436,            21298,\n            23293,            25181,            27973,            30520,\n              887,             1581,             3057,             4318,\n             7192,             8617,            10047,            13106,\n            16265,            17893,            20233,            22350,\n            24379,            26384,            28314,            30189,\n             2285,             3745,             5662,             7576,\n             9323,            11320,            13239,            15191,\n            17175,            19225,            21108,            22972,\n            24821,            26655,            28561,            30460,\n             1496,             2108,             3448,             6898,\n             8328,             9656,            11252,            12823,\n            14979,            16482,            18180,            20085,\n            22962,            25160,            27705,            29629,\n              575,             1261,             3861,             6627,\n             8294,            10809,            12705,            14768,\n            17076,            19047,            20978,            23055,\n            24972,            26703,            28720,            30345,\n             1682,             2213,             3882,             6238,\n             7208,             9646,            10877,            13431,\n            14805,            16213,            17941,            20873,\n            23550,            25765,            27756,            29461,\n              888,             1616,             3924,             5195,\n             7206,             8647,             9842,            11473,\n            16067,            18221,            20343,            22774,\n            24503,            26412,            28054,            29731,\n              805,             1454,             2683,             4472,\n             7936,             9360,            11398,            14345,\n            16205,            17832,            19453,            21646,\n            23899,            25928,            28387,            30463,\n             1640,             2383,             3484,             5082,\n             6032,             8606,            11640,            12966,\n            15842,            17368,            19346,            21182,\n            23638,            25889,            28368,            30299,\n             1632,             2204,             4510,             7580,\n             8718,            10512,            11962,            14096,\n            15640,            17194,            19143,            22247,\n            24563,            26561,            28604,            30509,\n             2043,             2612,             3985,             6851,\n             8038,             9514,            10979,            12789,\n            15426,            16728,            18899,            20277,\n            22902,            26209,            28711,            30618,\n             2224,             2798,             4465,             5320,\n             7108,             9436,            10986,            13222,\n            14599,            18317,            20141,            21843,\n            23601,            25700,            28184,            30582,\n              835,             1541,             4083,             5769,\n             7386,             9399,            10971,            12456,\n            15021,            18642,            20843,            23100,\n            25292,            26966,            28952,            30422,\n             1795,             2343,             4809,             5896,\n             7178,             8545,            10223,            13370,\n            14606,            16469,            18273,            20736,\n            23645,            26257,            28224,            30390,\n             1734,             2254,             4031,             5188,\n             6506,             7872,             9651,            13025,\n            14419,            17305,            19495,            22190,\n            24403,            26302,            28195,            30177,\n             1841,             2349,             3968,             4764,\n             6376,             9825,            11048,            13345,\n            14682,            16252,            18183,            21363,\n            23918,            26156,            28031,            29935,\n             1432,             2047,             5631,             6927,\n             8198,             9675,            11358,            13506,\n            14802,            16419,            18339,            22019,\n            24124,            26177,            28130,            30586,\n             1730,             2320,             3744,             4808,\n             6007,             9666,            10997,            13622,\n            15234,            17495,            20088,            22002,\n            23603,            25400,            27379,            29254,\n             1267,             1915,             5483,             6812,\n             8229,             9919,            11589,            13337,\n            14747,            17965,            20552,            22167,\n            24519,            26819,            28883,            30642,\n             1526,             2229,             4240,             7388,\n             8953,            10450,            11899,            13718,\n            16861,            18323,            20379,            22672,\n            24797,            26906,            28906,            30622,\n             2175,             2791,             4104,             6875,\n             8612,             9798,            12152,            13536,\n            15623,            17682,            19213,            21060,\n            24382,            26760,            28633,            30248,\n              454,             1231,             4339,             5738,\n             7550,             9006,            10320,            13525,\n            16005,            17849,            20071,            21992,\n            23949,            26043,            28245,            30175,\n             2250,             2791,             4230,             5283,\n             6762,            10607,            11879,            13821,\n            15797,            17264,            20029,            22266,\n            24588,            26437,            28244,            30419,\n             1696,             2216,             4308,             8385,\n             9766,            11030,            12556,            14099,\n            16322,            17640,            19166,            20590,\n            23967,            26858,            28798,            30562,\n             2452,             3236,             4369,             6118,\n             7156,             9003,            11509,            12796,\n            15749,            17291,            19491,            22241,\n            24530,            26474,            28273,            30073,\n             1811,             2541,             3555,             5480,\n             9123,            10527,            11894,            13659,\n            15262,            16899,            19366,            21069,\n            22694,            24314,            27256,            29983,\n             1553,             2246,             4559,             5500,\n             6754,             7874,            11739,            13571,\n            15188,            17879,            20281,            22510,\n            24614,            26649,            28786,            30755,\n             1982,             2768,             3834,             5964,\n             8732,             9908,            11797,            14813,\n            16311,            17946,            21097,            22851,\n            24456,            26304,            28166,            29755,\n             1824,             2529,             3817,             5449,\n             6854,             8714,            10381,            12286,\n            14194,            15774,            19524,            21374,\n            23695,            26069,            28096,            30212,\n             2212,             2854,             3947,             5898,\n             9930,            11556,            12854,            14788,\n            16328,            17700,            20321,            22098,\n            23672,            25291,            26976,            28586,\n             2023,             2599,             4024,             4916,\n             6613,            11149,            12457,            14626,\n            16320,            17822,            19673,            21172,\n            23115,            26051,            28825,            30758,\n             1628,             2206,             3467,             4364,\n             8679,            10173,            11864,            13679,\n            14998,            16938,            19207,            21364,\n            23850,            26115,            28124,            30273,\n             2014,             2603,             4114,             7254,\n             8516,            10043,            11822,            13503,\n            16329,            17826,            19697,            21280,\n            23151,            24661,            26807,            30161,\n             2376,             2980,             4422,             5770,\n             7016,             9723,            11125,            13516,\n            15485,            16985,            19160,            20587,\n            24401,            27180,            29046,            30647,\n             2454,             3502,             4624,             6019,\n             7632,             8849,            10792,            13964,\n            15523,            17085,            19611,            21238,\n            22856,            25108,            28106,            29890,\n             1573,             2274,             3308,             5999,\n             8977,            10104,            12457,            14258,\n            15749,            18180,            19974,            21253,\n            23045,            25058,            27741,            30315,\n             1943,             2730,             4140,             6160,\n             7491,             8986,            11309,            12775,\n            14820,            16558,            17909,            19757,\n            21512,            23605,            27274,            29527,\n             2021,             2582,             4494,             5835,\n             6993,             8245,             9827,            14733,\n            16462,            17894,            19647,            21083,\n            23764,            26667,            29072,            30990,\n             1052,             1775,             3218,             4378,\n             7666,             9403,            11248,            13327,\n            14972,            17962,            20758,            22354,\n            25071,            27209,            29001,            30609,\n             2218,             2866,             4223,             5352,\n             6581,             9980,            11587,            13121,\n            15193,            16583,            18386,            20080,\n            22013,            25317,            28127,            29880,\n             2146,             2840,             4397,             5840,\n             7449,             8721,            10512,            11936,\n            13595,            17253,            19310,            20891,\n            23417,            25627,            27749,            30231,\n             1972,             2619,             3756,             6367,\n             7641,             8814,            12286,            13768,\n            15309,            18036,            19557,            20904,\n            22582,            24876,            27800,            30440,\n             2005,             2577,             4272,             7373,\n             8558,            10223,            11770,            13402,\n            16502,            18000,            19645,            21104,\n            22990,            26806,            29505,            30942,\n             1153,             1822,             3724,             5443,\n             6990,             8702,            10289,            11899,\n            13856,            15315,            17601,            21064,\n            23692,            26083,            28586,            30639,\n             1304,             1869,             3318,             7195,\n             9613,            10733,            12393,            13728,\n            15822,            17474,            18882,            20692,\n            23114,            25540,            27684,            29244,\n             2093,             2691,             4018,             6658,\n             7947,             9147,            10497,            11881,\n            15888,            17821,            19333,            21233,\n            23371,            25234,            27553,            29998,\n              575,             1331,             5304,             6910,\n             8425,            10086,            11577,            13498,\n            16444,            18527,            20565,            22847,\n            24914,            26692,            28759,            30157,\n             1435,             2024,             3283,             4156,\n             7611,            10592,            12049,            13927,\n            15459,            18413,            20495,            22270,\n            24222,            26093,            28065,            30099,\n             1632,             2168,             5540,             7478,\n             8630,            10391,            11644,            14321,\n            15741,            17357,            18756,            20434,\n            22799,            26060,            28542,            30696,\n             1407,             2245,             3405,             5639,\n             9419,            10685,            12104,            13495,\n            15535,            18357,            19996,            21689,\n            24351,            26550,            28853,            30564,\n             1675,             2226,             4005,             8223,\n             9975,            11155,            12822,            14316,\n            16504,            18137,            19574,            21050,\n            22759,            24912,            28296,            30634,\n             1080,             1614,             3622,             7565,\n             8748,            10303,            11713,            13848,\n            15633,            17434,            19761,            21825,\n            23571,            25393,            27406,            29063,\n             1693,             2229,             3456,             4354,\n             5670,            10890,            12563,            14167,\n            15879,            17377,            19817,            21971,\n            24094,            26131,            28298,            30099,\n             2042,             2959,             4195,             5740,\n             7106,             8267,            11126,            14973,\n            16914,            18295,            20532,            21982,\n            23711,            25769,            27609,            29351,\n              984,             1612,             3808,             5265,\n             6885,             8411,             9547,            10889,\n            12522,            16520,            19549,            21639,\n            23746,            26058,            28310,            30374,\n             2036,             2538,             4166,             7761,\n             9146,            10412,            12144,            13609,\n            15588,            17169,            18559,            20113,\n            21820,            24313,            28029,            30612,\n             1871,             2355,             4061,             5143,\n             7464,            10129,            11941,            15001,\n            16680,            18354,            19957,            22279,\n            24861,            26872,            28988,            30615,\n             2566,             3161,             4643,             6227,\n             7406,             9970,            11618,            13416,\n            15889,            17364,            19121,            20817,\n            22592,            24720,            28733,            31082,\n             1700,             2327,             4828,             5939,\n             7567,             9154,            11087,            12771,\n            14209,            16121,            20222,            22671,\n            24648,            26656,            28696,            30745,\n             3169,             3873,             5046,             6868,\n             8184,             9480,            12335,            14068,\n            15774,            17971,            20231,            21711,\n            23520,            25245,            27026,            28730,\n             1564,             2391,             4229,             6730,\n             8905,            10459,            13026,            15033,\n            17265,            19809,            21849,            23741,\n            25490,            27312,            29061,            30527,\n             2864,             3559,             4719,             6441,\n             9592,            11055,            12763,            14784,\n            16428,            18164,            20486,            22262,\n            24183,            26263,            28383,            30224,\n             2673,             3449,             4581,             5983,\n             6863,             8311,            12464,            13911,\n            15738,            17791,            19416,            21182,\n            24025,            26561,            28723,            30440,\n             2419,             3049,             4274,             6384,\n             8564,             9661,            11288,            12676,\n            14447,            17578,            19816,            21231,\n            23099,            25270,            26899,            28926,\n             1278,             2001,             3000,             5353,\n             9995,            11777,            13018,            14570,\n            16050,            17762,            19982,            21617,\n            23371,            25083,            27656,            30172,\n              932,             1624,             2798,             4570,\n             8592,             9988,            11552,            13050,\n            16921,            18677,            20415,            22810,\n            24817,            26819,            28804,            30385,\n             2324,             2973,             4156,             5702,\n             6919,             8806,            10259,            12503,\n            15015,            16567,            19418,            21375,\n            22943,            24550,            27024,            29849,\n             1564,             2373,             3455,             4907,\n             5975,             7436,            11786,            14505,\n            16107,            18148,            20019,            21653,\n            23740,            25814,            28578,            30372,\n             3025,             3729,             4866,             6520,\n             9487,            10943,            12358,            14258,\n            16174,            17501,            19476,            21408,\n            23227,            24906,            27347,            29407,\n             1270,             1965,             6802,             7995,\n             9204,            10828,            12507,            14230,\n            15759,            17860,            20369,            22502,\n            24633,            26514,            28535,            30525,\n             2210,             2749,             4266,             7487,\n             9878,            11018,            12823,            14431,\n            16247,            18626,            20450,            22054,\n            23739,            25291,            27074,            29169,\n             1275,             1926,             4330,             6573,\n             8441,            10920,            13260,            15008,\n            16927,            18573,            20644,            22217,\n            23983,            25474,            27372,            28645,\n             3015,             3670,             5086,             6372,\n             7888,             9309,            10966,            12642,\n            14495,            16172,            18080,            19972,\n            22454,            24899,            27362,            29975,\n             2882,             3733,             5113,             6482,\n             8125,             9685,            11598,            13288,\n            15405,            17192,            20178,            22426,\n            24801,            27014,            29212,            30811,\n             2300,             2968,             4101,             5442,\n             6327,             7910,            12455,            13862,\n            15747,            17505,            19053,            20679,\n            22615,            24658,            27499,            30065,\n             2257,             2940,             4430,             5991,\n             7042,             8364,             9414,            11224,\n            15723,            17420,            19253,            21469,\n            23915,            26053,            28430,            30384,\n             1227,             2045,             3818,             5011,\n             6990,             9231,            11024,            13011,\n            17341,            19017,            20583,            22799,\n            25195,            26876,            29351,            30805,\n             1354,             1924,             3789,             8077,\n            10453,            11639,            13352,            14817,\n            16743,            18189,            20095,            22014,\n            24593,            26677,            28647,            30256,\n             3142,             4049,             6197,             7417,\n             8753,            10156,            11533,            13181,\n            15947,            17655,            19606,            21402,\n            23487,            25659,            28123,            30304,\n             1317,             2263,             4725,             7611,\n             9667,            11634,            14143,            16258,\n            18724,            20698,            22379,            24007,\n            25775,            27251,            28930,            30593,\n             1570,             2323,             3818,             6215,\n             9893,            11556,            13070,            14631,\n            16152,            18290,            21386,            23346,\n            25114,            26923,            28712,            30168,\n             2297,             3905,             6287,             8558,\n            10668,            12766,            15019,            17102,\n            19036,            20677,            22341,            23871,\n            25478,            27085,            28851,            30520,\n             1915,             2507,             4033,             5749,\n             7059,             8871,            10659,            12198,\n            13937,            15383,            16869,            18707,\n            23175,            25818,            28514,            30501,\n             2404,             2918,             5190,             6252,\n             7426,             9887,            12387,            14795,\n            16754,            18368,            20338,            22003,\n            24236,            26456,            28490,            30397,\n             1621,             2227,             3479,             5085,\n             9425,            12892,            14246,            15652,\n            17205,            18674,            20446,            22209,\n            23778,            25867,            27931,            30093,\n             1869,             2390,             4105,             7021,\n            11221,            12775,            14059,            15590,\n            17024,            18608,            20595,            22075,\n            23649,            25154,            26914,            28671,\n             2551,             3252,             4688,             6562,\n             7869,             9125,            10475,            11800,\n            15402,            18780,            20992,            22555,\n            24289,            25968,            27465,            29232,\n             2705,             3493,             4735,             6360,\n             7905,             9352,            11538,            13430,\n            15239,            16919,            18619,            20094,\n            21800,            23342,            25200,            29257,\n             2166,             2791,             4011,             5081,\n             5896,             9038,            13407,            14703,\n            16543,            18189,            19896,            21857,\n            24872,            26971,            28955,            30514,\n             1865,             3021,             4696,             6534,\n             8343,             9914,            12789,            14103,\n            16533,            17729,            21340,            22439,\n            24873,            26330,            28428,            30154,\n             3369,             4345,             6573,             8763,\n            10309,            11713,            13367,            14784,\n            16483,            18145,            19839,            21247,\n            23292,            25477,            27555,            29447,\n             1265,             2184,             5443,             7893,\n            10591,            13139,            15105,            16639,\n            18402,            19826,            21419,            22995,\n            24719,            26437,            28363,            30125,\n             1584,             2004,             3535,             4450,\n             8662,            10764,            12832,            14978,\n            16972,            18794,            20932,            22547,\n            24636,            26521,            28701,            30567,\n             3419,             4528,             6602,             7890,\n             9508,            10875,            12771,            14357,\n            16051,            18330,            20630,            22490,\n            25070,            26936,            28946,            30542,\n             1726,             2252,             4597,             6950,\n             8379,             9823,            11363,            12794,\n            14306,            15476,            16798,            18018,\n            21671,            25550,            28148,            30367,\n             3385,             3870,             5307,             6388,\n             7141,             8684,            12695,            14939,\n            16480,            18277,            20537,            22048,\n            23947,            25965,            28214,            29956,\n             2771,             3306,             4450,             5560,\n             6453,             9493,            13548,            14754,\n            16743,            18447,            20028,            21736,\n            23746,            25353,            27141,            29066,\n             3028,             3900,             6617,             7893,\n             9211,            10480,            12047,            13583,\n            15182,            16662,            18502,            20092,\n            22190,            24358,            26302,            28957,\n             2000,             2550,             4067,             6837,\n             9628,            11002,            12594,            14098,\n            15589,            17195,            18679,            20099,\n            21530,            23085,            24641,            29022,\n             2844,             3302,             5103,             6107,\n             6911,             8598,            12416,            14054,\n            16026,            18567,            20672,            22270,\n            23952,            25771,            27658,            30026,\n             4043,             5150,             7268,             9056,\n            10916,            12638,            14543,            16184,\n            17948,            19691,            21357,            22981,\n            24825,            26591,            28479,            30233,\n             2109,             2625,             4320,             5525,\n             7454,            10220,            12980,            14698,\n            17627,            19263,            20485,            22381,\n            24279,            25777,            27847,            30458,\n             1550,             2667,             6473,             9496,\n            10985,            12352,            13795,            15233,\n            17099,            18642,            20461,            22116,\n            24197,            26291,            28403,            30132,\n             2411,             3084,             4145,             5394,\n             6367,             8154,            13125,            16049,\n            17561,            19125,            21258,            22762,\n            24459,            26317,            28255,            29702,\n             4159,             4516,             5956,             7635,\n             8254,             8980,            11208,            14133,\n            16210,            17875,            20196,            21864,\n            23840,            25747,            28058,            30012,\n             2026,             2431,             2845,             3618,\n             7950,             9802,            12721,            14460,\n            16576,            18984,            21376,            23319,\n            24961,            26718,            28971,            30640,\n             3429,             3833,             4472,             4912,\n             7723,            10386,            12981,            15322,\n            16699,            18807,            20778,            22551,\n            24627,            26494,            28334,            30482,\n             4740,             5169,             5796,             6485,\n             6998,             8830,            11777,            14414,\n            16831,            18413,            20789,            22369,\n            24236,            25835,            27807,            30021,\n              150,              168,              -17,             -107,\n             -142,             -229,             -320,             -406,\n             -503,             -620,             -867,             -935,\n             -902,             -680,             -398,             -114,\n             -398,             -355,               49,              255,\n              114,              260,              399,              264,\n              317,              431,              514,              531,\n              435,              356,              238,              106,\n              -43,              -36,             -169,             -224,\n             -391,             -633,             -776,             -970,\n             -844,             -455,             -181,              -12,\n               85,               85,              164,              195,\n              122,               85,             -158,             -640,\n             -903,                9,                7,             -124,\n              149,               32,              220,              369,\n              242,              115,               79,               84,\n             -146,             -216,              -70,             1024,\n              751,              574,              440,              377,\n              352,              203,               30,               16,\n               -3,               81,              161,              100,\n             -148,             -176,              933,              750,\n              404,              171,               -2,             -146,\n             -411,             -442,             -541,             -552,\n             -442,             -269,             -240,              -52,\n              603,              635,              405,              178,\n              215,               19,             -153,             -167,\n             -290,             -219,              151,              271,\n              151,              119,              303,              266,\n              100,               69,             -293,             -657,\n              939,              659,              442,              351,\n              132,               98,              -16,               -1,\n             -135,             -200,             -223,              -89,\n              167,              154,              172,              237,\n              -45,             -183,             -228,             -486,\n              263,              608,              158,             -125,\n             -390,             -227,             -118,               43,\n             -457,             -392,             -769,             -840,\n               20,             -117,             -194,             -189,\n             -173,             -173,              -33,               32,\n              174,              144,              115,              167,\n               57,               44,               14,              147,\n               96,              -54,             -142,             -129,\n             -254,             -331,              304,              310,\n              -52,             -419,             -846,            -1060,\n              -88,             -123,             -202,             -343,\n             -554,             -961,             -951,              327,\n              159,               81,              255,              227,\n              120,              203,              256,              192,\n              164,              224,              290,              195,\n              216,              209,              128,              832,\n             1028,              889,              698,              504,\n              408,              355,              218,               32,\n             -115,              -84,             -276,             -100,\n             -312,             -484,              899,              682,\n              465,              456,              241,              -12,\n             -275,             -425,             -461,             -367,\n              -33,              -28,             -102,             -194,\n             -527,              863,              906,              463,\n              245,               13,             -212,             -305,\n             -105,              163,              279,              176,\n               93,               67,              115,              192,\n               61,              -50,             -132,             -175,\n             -224,             -271,             -629,             -252,\n             1158,              972,              638,              280,\n              300,              326,              143,             -152,\n             -214,             -287,               53,              -42,\n             -236,             -352,             -423,             -248,\n             -129,             -163,             -178,             -119,\n               85,               57,              514,              382,\n              374,              402,              424,              423,\n              271,              197,               97,               40,\n               39,              -97,             -191,             -164,\n             -230,             -256,             -410,              396,\n              327,              127,               10,             -119,\n             -167,             -291,             -274,             -141,\n              -99,             -226,             -218,             -139,\n             -224,             -209,             -268,             -442,\n             -413,              222,               58,              521,\n              344,              258,               76,              -42,\n             -142,             -165,             -123,              -92,\n               47,                8,               -3,             -191,\n              -11,             -164,             -167,             -351,\n             -740,              311,              538,              291,\n              184,               29,             -105,                9,\n              -30,              -54,              -17,              -77,\n             -271,             -412,             -622,             -648,\n              476,              186,              -66,             -197,\n              -73,              -94,              -15,               47,\n               28,              112,              -58,              -33,\n               65,               19,               84,               86,\n              276,              114,              472,              786,\n              799,              625,              415,              178,\n              -35,              -26,                5,                9,\n               83,               39,               37,               39,\n             -184,             -374,             -265,             -362,\n             -501,              337,              716,              478,\n              -60,             -125,             -163,              362,\n               17,             -122,             -233,              279,\n              138,              157,              318,              193,\n              189,              209,              266,              252,\n              -46,              -56,             -277,             -429,\n              464,              386,              142,               44,\n              -43,               66,              264,              182,\n               47,               14,              -26,              -79,\n               49,               15,             -128,             -203,\n             -400,             -478,              325,               27,\n              234,              411,              205,              129,\n               12,               58,              123,               57,\n              171,              137,               96,              128,\n              -32,              134,              -12,               57,\n              119,               26,              -22,             -165,\n             -500,             -701,             -528,             -116,\n               64,               -8,               97,               -9,\n             -162,              -66,             -156,             -194,\n             -303,             -546,             -341,              546,\n              358,               95,               45,               76,\n              270,              403,              205,              100,\n              123,               50,              -53,             -144,\n             -110,              -13,               32,             -228,\n             -130,              353,              296,               56,\n             -372,             -253,              365,               73,\n               10,              -34,             -139,             -191,\n              -96,                5,               44,              -85,\n             -179,             -129,             -192,             -246,\n              -85,             -110,             -155,              -44,\n              -27,              145,              138,               79,\n               32,             -148,             -577,             -634,\n              191,               94,               -9,              -35,\n              -77,              -84,              -56,             -171,\n             -298,             -271,             -243,             -156,\n             -328,             -235,              -76,             -128,\n             -121,              129,               13,              -22,\n               32,               45,             -248,              -65,\n              193,              -81,              299,               57,\n             -147,              192,             -165,             -354,\n             -334,             -106,             -156,              -40,\n               -3,              -68,              124,             -257,\n               78,              124,              170,              412,\n              227,              105,             -104,               12,\n              154,              250,              274,              258,\n                4,              -27,              235,              152,\n               51,              338,              300,                7,\n             -314,             -411,              215,              170,\n               -9,              -93,              -77,               76,\n               67,               54,              200,              315,\n              163,               72,              -91,             -402,\n              158,              187,             -156,              -91,\n              290,              267,              167,               91,\n              140,              171,              112,                9,\n              -42,             -177,             -440,              385,\n               80,               15,              172,              129,\n               41,             -129,             -372,              -24,\n              -75,              -30,             -170,               10,\n             -118,               57,               78,             -101,\n              232,              161,              123,              256,\n              277,              101,             -192,             -629,\n             -100,              -60,             -232,               66,\n               13,              -13,              -80,             -239,\n              239,               37,               32,               89,\n             -319,             -579,              450,              360,\n                3,              -29,             -299,              -89,\n              -54,             -110,             -246,             -164,\n                6,             -188,              338,              176,\n              -92,              197,              137,              134,\n               12,               -2,               56,             -183,\n              114,              -36,             -131,             -204,\n               75,              -25,             -174,              191,\n              -15,             -290,             -429,             -267,\n               79,               37,              106,               23,\n             -384,              425,               70,              -14,\n              212,              105,               15,               -2,\n              -42,              -37,             -123,              108,\n               28,              -48,              193,              197,\n              173,              -33,               37,               73,\n              -57,              256,              137,              -58,\n             -430,             -228,              217,              -51,\n              -10,              -58,               -6,               22,\n              104,               61,             -119,              169,\n              144,               16,              -46,             -394,\n               60,              454,              -80,             -298,\n              -65,               25,                0,              -24,\n              -65,             -417,              465,              276,\n               -3,             -194,              -13,              130,\n               19,               -6,              -21,              -24,\n             -180,              -53,              -85,               20,\n              118,              147,              113,              -75,\n             -289,              226,             -122,              227,\n              270,              125,              109,              197,\n              125,              138,               44,               60,\n               25,              -55,             -167,              -32,\n             -139,             -193,             -173,             -316,\n              287,             -208,              253,              239,\n               27,              -80,             -188,              -28,\n             -182,             -235,              156,             -117,\n              128,              -48,              -58,             -226,\n              172,              181,              167,               19,\n               62,               10,                2,              181,\n              151,              108,              -16,              -11,\n              -78,             -331,              411,              133,\n               17,              104,               64,             -184,\n               24,              -30,               -3,             -283,\n              121,              204,               -8,             -199,\n              -21,              -80,             -169,             -157,\n             -191,             -136,               81,              155,\n               14,             -131,              244,               74,\n              -57,              -47,             -280,              347,\n              111,              -77,             -128,             -142,\n             -194,             -125,               -6,              -68,\n               91,                1,               23,               14,\n             -154,              -34,               23,              -38,\n             -343,              503,              146,              -38,\n              -46,              -41,               58,               31,\n               63,              -48,             -117,               45,\n               28,                1,              -89,               -5,\n              -44,              -29,             -448,              487,\n              204,               81,               46,             -106,\n             -302,              380,              120,              -38,\n              -12,              -39,               70,               -3,\n               25,              -65,               30,              -11,\n               34,              -15,               22,             -115,\n                0,              -79,              -83,               45,\n              114,               43,              150,               36,\n              233,              149,              195,                5,\n               25,              -52,             -475,              274,\n               28,              -39,               -8,              -66,\n             -255,              258,               56,              143,\n              -45,             -190,              165,              -60,\n               20,                2,              125,             -129,\n               51,               -8,             -335,              288,\n               38,               59,               25,              -42,\n               23,             -118,             -112,               11,\n              -55,             -133,             -109,               24,\n             -105,               78,              -64,             -245,\n              202,              -65,             -127,              162,\n               40,              -94,               89,              -85,\n             -119,             -103,               97,                9,\n              -70,              -28,              194,               86,\n             -112,              -92,             -114,               74,\n              -49,               46,              -84,             -178,\n              113,               52,             -205,              333,\n               88,              222,               56,              -55,\n               13,               86,                4,              -77,\n              224,              114,             -105,              112,\n              125,              -29,              -18,             -144,\n               22,              -58,              -99,               28,\n              114,              -66,              -32,             -169,\n             -314,              285,               72,              -74,\n              179,               28,              -79,             -182,\n               13,              -55,              147,               13,\n               12,              -54,               31,              -84,\n              -17,              -75,             -228,               83,\n             -375,              436,              110,              -63,\n              -27,             -136,              169,              -56,\n               -8,             -171,              184,              -42,\n              148,               68,              204,              235,\n              110,             -229,               91,              171,\n              -43,               -3,              -26,              -99,\n             -111,               71,             -170,              202,\n              -67,              181,              -37,              109,\n             -120,                3,              -55,             -260,\n              -16,              152,               91,              142,\n               42,               44,              134,               47,\n               17,              -35,               22,               79,\n             -169,               41,               46,              277,\n              -93,              -49,             -126,               37,\n             -103,              -34,              -22,              -90,\n             -134,             -205,               92,               -9,\n                1,             -195,             -239,               45,\n               54,               18,              -23,               -1,\n              -80,              -98,              -20,             -261,\n              306,               72,               20,              -89,\n             -217,               11,                6,              -82,\n               89,               13,             -129,              -89,\n               83,              -71,              -55,              130,\n              -98,             -146,              -27,              -57,\n               53,              275,               17,              170,\n               -5,              -54,              132,              -64,\n               72,              160,             -125,             -168,\n               72,               40,              170,               78,\n              248,              116,               20,               84,\n               31,              -34,              190,               38,\n               13,             -106,              225,               27,\n             -168,               24,             -157,             -122,\n              165,               11,             -161,             -213,\n              -12,              -51,             -101,               42,\n              101,               27,               55,              111,\n               75,               71,              -96,               -1,\n               65,             -277,              393,              -26,\n              -44,              -68,              -84,              -66,\n              -95,              235,              179,              -25,\n              -41,               27,              -91,             -128,\n             -222,              146,              -72,              -30,\n              -24,               55,             -126,              -68,\n              -58,             -127,               13,              -97,\n             -106,              174,             -100,              155,\n              101,             -146,              -21,              261,\n               22,               38,              -66,               65,\n                4,               70,               64,              144,\n               59,              213,               71,             -337,\n              303,              -52,               51,              -56,\n                1,               10,              -15,               -5,\n               34,               52,              228,              131,\n              161,             -127,             -214,              238,\n              123,               64,             -147,              -50,\n              -34,             -127,              204,              162,\n               85,               41,                5,             -140,\n               73,             -150,               56,              -96,\n              -66,              -20,                2,             -235,\n               59,              -22,             -107,              150,\n              -16,              -47,               -4,               81,\n              -67,              167,              149,              149,\n             -157,              288,             -156,              -27,\n               -8,               18,               83,              -24,\n              -41,             -167,              158,             -100,\n               93,               53,              201,               15,\n               42,              266,              278,              -12,\n               -6,              -37,               85,                6,\n               20,             -188,             -271,              107,\n              -13,              -80,               51,              202,\n              173,              -69,               78,             -188,\n               46,                4,              153,               12,\n             -138,              169,                5,              -58,\n             -123,             -108,             -243,              150,\n               10,             -191,              246,              -15,\n               38,               25,              -10,               14,\n               61,               50,             -206,             -215,\n             -220,               90,                5,             -149,\n             -219,               56,              142,               24,\n             -376,               77,              -80,               75,\n                6,               42,             -101,               16,\n               56,               14,              -57,                3,\n              -17,               80,               57,              -36,\n               88,              -59,              -97,              -19,\n             -148,               46,             -219,              226,\n              114,               -4,              -72,              -15,\n               37,              -49,              -28,              247,\n               44,              123,               47,             -122,\n              -38,               17,                4,             -113,\n              -32,             -224,              154,             -134,\n              196,               71,             -267,              -85,\n               28,              -70,               89,             -120,\n               99,               -2,               64,               76,\n             -166,              -48,              189,              -35,\n              -92,             -169,             -123,              339,\n               38,              -25,               38,              -35,\n              225,             -139,              -50,              -63,\n              246,               60,             -185,             -109,\n              -49,              -53,             -167,               51,\n              149,               60,             -101,              -33,\n               25,              -76,              120,               32,\n              -30,              -83,              102,               91,\n             -186,             -261,              131,             -197\n};\n\nconst SKP_Silk_NLSF_CBS SKP_Silk_NLSF_CB0_16_Stage_info[ NLSF_MSVQ_CB0_16_STAGES ] =\n{\n        { 128, &SKP_Silk_NLSF_MSVQ_CB0_16_Q15[ 16 *   0 ], &SKP_Silk_NLSF_MSVQ_CB0_16_rates_Q5[   0 ] },\n        {  16, &SKP_Silk_NLSF_MSVQ_CB0_16_Q15[ 16 * 128 ], &SKP_Silk_NLSF_MSVQ_CB0_16_rates_Q5[ 128 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB0_16_Q15[ 16 * 144 ], &SKP_Silk_NLSF_MSVQ_CB0_16_rates_Q5[ 144 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB0_16_Q15[ 16 * 152 ], &SKP_Silk_NLSF_MSVQ_CB0_16_rates_Q5[ 152 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB0_16_Q15[ 16 * 160 ], &SKP_Silk_NLSF_MSVQ_CB0_16_rates_Q5[ 160 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB0_16_Q15[ 16 * 168 ], &SKP_Silk_NLSF_MSVQ_CB0_16_rates_Q5[ 168 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB0_16_Q15[ 16 * 176 ], &SKP_Silk_NLSF_MSVQ_CB0_16_rates_Q5[ 176 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB0_16_Q15[ 16 * 184 ], &SKP_Silk_NLSF_MSVQ_CB0_16_rates_Q5[ 184 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB0_16_Q15[ 16 * 192 ], &SKP_Silk_NLSF_MSVQ_CB0_16_rates_Q5[ 192 ] },\n        {  16, &SKP_Silk_NLSF_MSVQ_CB0_16_Q15[ 16 * 200 ], &SKP_Silk_NLSF_MSVQ_CB0_16_rates_Q5[ 200 ] }\n};\n\nconst SKP_Silk_NLSF_CB_struct SKP_Silk_NLSF_CB0_16 =\n{\n        NLSF_MSVQ_CB0_16_STAGES,\n        SKP_Silk_NLSF_CB0_16_Stage_info,\n        SKP_Silk_NLSF_MSVQ_CB0_16_ndelta_min_Q15,\n        SKP_Silk_NLSF_MSVQ_CB0_16_CDF,\n        SKP_Silk_NLSF_MSVQ_CB0_16_CDF_start_ptr,\n        SKP_Silk_NLSF_MSVQ_CB0_16_CDF_middle_idx\n};\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_tables_NLSF_CB1_10.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/**********************************************/\n/* This file has been automatically generated */\n/*                                            */\n/* ROM usage:  0.19 + 1.61 kB                 */\n/**********************************************/\n\n#include \"SKP_Silk_structs.h\"\n#include \"SKP_Silk_tables_NLSF_CB1_10.h\"\n#include \"SKP_Silk_tables.h\"\n\nconst SKP_uint16 SKP_Silk_NLSF_MSVQ_CB1_10_CDF[ NLSF_MSVQ_CB1_10_VECTORS + NLSF_MSVQ_CB1_10_STAGES ] =\n{\n            0,\n        17096,\n        24130,\n        28997,\n        33179,\n        36696,\n        40213,\n        42493,\n        44252,\n        45973,\n        47551,\n        49095,\n        50542,\n        51898,\n        53196,\n        54495,\n        55685,\n        56851,\n        57749,\n        58628,\n        59435,\n        60207,\n        60741,\n        61220,\n        61700,\n        62179,\n        62659,\n        63138,\n        63617,\n        64097,\n        64576,\n        65056,\n        65535,\n            0,\n        20378,\n        33032,\n        40395,\n        46721,\n        51707,\n        56585,\n        61157,\n        65535,\n            0,\n        15055,\n        25472,\n        35447,\n        42501,\n        48969,\n        54773,\n        60212,\n        65535,\n            0,\n        12069,\n        22440,\n        32812,\n        40145,\n        46870,\n        53595,\n        59630,\n        65535,\n            0,\n        10839,\n        19954,\n        27957,\n        35961,\n        43965,\n        51465,\n        58805,\n        65535,\n            0,\n         8933,\n        17674,\n        26415,\n        34785,\n        42977,\n        50820,\n        58496,\n        65535\n};\n\nconst SKP_uint16 * const SKP_Silk_NLSF_MSVQ_CB1_10_CDF_start_ptr[ NLSF_MSVQ_CB1_10_STAGES ] =\n{\n     &SKP_Silk_NLSF_MSVQ_CB1_10_CDF[   0 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_10_CDF[  33 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_10_CDF[  42 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_10_CDF[  51 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_10_CDF[  60 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_10_CDF[  69 ]\n};\n\nconst SKP_int SKP_Silk_NLSF_MSVQ_CB1_10_CDF_middle_idx[ NLSF_MSVQ_CB1_10_STAGES ] =\n{\n       5,\n       3,\n       4,\n       4,\n       5,\n       5\n};\n\nconst SKP_int16 SKP_Silk_NLSF_MSVQ_CB1_10_rates_Q5[ NLSF_MSVQ_CB1_10_VECTORS ] =\n{\n               62,              103,\n              120,              127,\n              135,              135,\n              155,              167,\n              168,              172,\n              173,              176,\n              179,              181,\n              181,              185,\n              186,              198,\n              199,              203,\n              205,              222,\n              227,              227,\n              227,              227,\n              227,              227,\n              227,              227,\n              227,              227,\n               54,               76,\n              101,              108,\n              119,              120,\n              123,              125,\n               68,               85,\n               87,              103,\n              107,              112,\n              115,              116,\n               78,               85,\n               85,              101,\n              105,              105,\n              110,              111,\n               83,               91,\n               97,               97,\n               97,              100,\n              101,              105,\n               92,               93,\n               93,               95,\n               96,               98,\n               99,              103\n};\n\nconst SKP_int SKP_Silk_NLSF_MSVQ_CB1_10_ndelta_min_Q15[ 10 + 1 ] =\n{\n              462,\n                3,\n               64,\n               74,\n               98,\n               50,\n               97,\n               68,\n              120,\n               53,\n              639\n};\n\nconst SKP_int16 SKP_Silk_NLSF_MSVQ_CB1_10_Q15[ 10 * NLSF_MSVQ_CB1_10_VECTORS ] =\n{\n             1877,             4646,\n             7712,            10745,\n            13964,            17028,\n            20239,            23182,\n            26471,            29287,\n             1612,             3278,\n             7086,             9975,\n            13228,            16264,\n            19596,            22690,\n            26037,            28965,\n             2169,             3830,\n             6460,             8958,\n            11960,            14750,\n            18408,            21659,\n            25018,            28043,\n             3680,             6024,\n             8986,            12256,\n            15201,            18188,\n            21741,            24460,\n            27484,            30059,\n             2584,             5187,\n             7799,            10902,\n            13179,            15765,\n            19017,            22431,\n            25891,            28698,\n             3731,             5751,\n             8650,            11742,\n            15090,            17407,\n            20391,            23421,\n            26228,            29247,\n             2107,             6323,\n             8915,            12226,\n            14775,            17791,\n            20664,            23679,\n            26829,            29353,\n             1677,             2870,\n             5386,             8077,\n            11817,            15176,\n            18657,            22006,\n            25513,            28689,\n             2111,             3625,\n             7027,            10588,\n            14059,            17193,\n            21137,            24260,\n            27577,            30036,\n             2428,             4010,\n             5765,             9376,\n            13805,            15821,\n            19444,            22389,\n            25295,            29310,\n             2256,             4628,\n             8377,            12441,\n            15283,            19462,\n            22257,            25551,\n            28432,            30304,\n             2352,             3675,\n             6129,            11868,\n            14551,            16655,\n            19624,            21883,\n            26526,            28849,\n             5243,             7248,\n            10558,            13269,\n            15651,            17919,\n            21141,            23827,\n            27102,            29519,\n             4422,             6725,\n            10449,            13273,\n            16124,            19921,\n            22826,            26061,\n            28763,            30583,\n             4508,             6291,\n             9504,            11809,\n            13827,            15950,\n            19077,            22084,\n            25740,            28658,\n             2540,             4297,\n             8579,            13578,\n            16634,            19101,\n            21547,            23887,\n            26777,            29146,\n             3377,             6358,\n            10224,            14518,\n            17905,            21056,\n            23637,            25784,\n            28161,            30109,\n             4177,             5942,\n             8159,            10108,\n            12130,            15470,\n            20191,            23326,\n            26782,            29359,\n             2492,             3801,\n             6144,             9825,\n            16000,            18671,\n            20893,            23663,\n            25899,            28974,\n             3011,             4727,\n             6834,            10505,\n            12465,            14496,\n            17065,            20052,\n            25265,            28057,\n             4149,             7197,\n            12338,            15076,\n            18002,            20190,\n            22187,            24723,\n            27083,            29125,\n             2975,             4578,\n             6448,             8378,\n             9671,            13225,\n            19502,            22277,\n            26058,            28850,\n             4102,             5760,\n             7744,             9484,\n            10744,            12308,\n            14677,            19607,\n            24841,            28381,\n             4931,             9287,\n            12477,            13395,\n            13712,            14351,\n            16048,            19867,\n            24188,            28994,\n             4141,             7867,\n            13140,            17720,\n            20064,            21108,\n            21692,            22722,\n            23736,            27449,\n             4011,             8720,\n            13234,            16206,\n            17601,            18289,\n            18524,            19689,\n            23234,            27882,\n             3420,             5995,\n            11230,            15117,\n            15907,            16783,\n            17762,            23347,\n            26898,            29946,\n             3080,             6786,\n            10465,            13676,\n            18059,            23615,\n            27058,            29082,\n            29563,            29905,\n             3038,             5620,\n             9266,            12870,\n            18803,            19610,\n            20010,            20802,\n            23882,            29306,\n             3314,             6420,\n             9046,            13262,\n            15869,            23117,\n            23667,            24215,\n            24487,            25915,\n             3469,             6963,\n            10103,            15282,\n            20531,            23240,\n            25024,            26021,\n            26736,            27255,\n             3041,             6459,\n             9777,            12896,\n            16315,            19410,\n            24070,            29353,\n            31795,            32075,\n             -200,             -134,\n             -113,             -204,\n             -347,             -440,\n             -352,             -211,\n             -418,             -172,\n             -313,               59,\n              495,              772,\n              721,              614,\n              334,              444,\n              225,              242,\n              161,               16,\n              274,              564,\n              -73,             -188,\n             -395,             -171,\n              777,              508,\n             1340,             1145,\n              699,              196,\n              223,              173,\n               90,               25,\n              -26,               18,\n              133,             -105,\n             -360,             -277,\n              859,              634,\n               41,             -557,\n             -768,             -926,\n             -601,            -1021,\n            -1189,             -365,\n              225,              107,\n              374,              -50,\n              433,              417,\n              156,               39,\n             -597,            -1397,\n            -1594,             -592,\n             -485,             -292,\n              253,               87,\n               -0,               -6,\n              -25,             -345,\n             -240,              120,\n             1261,              946,\n              166,             -277,\n              241,              167,\n              170,              429,\n              518,              714,\n              602,              254,\n              134,               92,\n             -152,             -324,\n             -394,               49,\n             -151,             -304,\n             -724,             -657,\n             -162,             -369,\n              -35,                3,\n               -2,             -312,\n             -200,              -92,\n             -227,              242,\n              628,              565,\n             -124,             1056,\n              770,              101,\n              -84,              -33,\n                4,             -192,\n             -272,                5,\n             -627,             -977,\n              419,              472,\n               53,             -103,\n              145,              322,\n              -95,              -31,\n             -100,             -303,\n             -560,            -1067,\n             -413,              714,\n              283,                2,\n             -223,             -367,\n              523,              360,\n              -38,             -115,\n              378,             -591,\n             -718,              448,\n             -481,             -274,\n              180,              -88,\n             -581,             -157,\n             -696,            -1265,\n              394,             -479,\n              -23,              124,\n              -43,               19,\n             -113,             -236,\n             -412,             -659,\n             -200,                2,\n              -69,             -342,\n              199,               55,\n               58,              -36,\n              -51,              -62,\n              507,              507,\n              427,              442,\n               36,              601,\n             -141,               68,\n              274,              274,\n               68,              -12,\n               -4,               71,\n             -193,             -464,\n             -425,             -383,\n              408,              203,\n             -337,              236,\n              410,              -59,\n              -25,             -341,\n             -449,               28,\n               -9,               90,\n              332,              -14,\n             -905,               96,\n             -540,             -242,\n              679,              -59,\n              192,              -24,\n               60,             -217,\n                5,              -37,\n              179,              -20,\n              311,              519,\n              274,               72,\n             -326,            -1030,\n             -262,              213,\n              380,               82,\n              328,              411,\n             -540,              574,\n             -283,              151,\n              181,             -402,\n             -278,             -240,\n             -110,             -227,\n             -264,              -89,\n             -250,             -259,\n              -27,              106,\n             -239,              -98,\n             -390,              118,\n               61,              104,\n              294,              532,\n               92,              -13,\n               60,             -233,\n              335,              541,\n              307,              -26,\n             -110,              -91,\n             -231,             -460,\n              170,              201,\n               96,             -372,\n              132,              435,\n             -302,              216,\n             -279,              -41,\n               74,              190,\n              368,              273,\n             -186,             -608,\n             -157,              159,\n               12,              278,\n              245,              307,\n               25,             -187,\n              -16,               55,\n               30,             -163,\n              548,             -307,\n              106,               -5,\n               27,              330,\n             -416,              475,\n              438,             -235,\n              104,              137,\n               21,               -5,\n             -300,             -468,\n              521,             -347,\n              170,             -200,\n             -219,              308,\n             -122,             -133,\n              219,              -16,\n              359,              412,\n              -89,             -111,\n               48,              322,\n              142,              177,\n             -286,             -127,\n              -39,              -63,\n              -42,             -451,\n              160,              308,\n              -57,              193,\n              -48,               74,\n             -346,               59,\n              -27,               27,\n             -469,             -277,\n             -344,              282,\n              262,              122,\n              171,             -249,\n               27,              258,\n              188,               -3,\n               67,             -206,\n             -284,              291,\n             -117,              -88,\n             -477,              375,\n               50,              106,\n               99,             -182,\n              438,             -376,\n             -401,              -49,\n              119,              -23,\n              -10,              -48,\n             -116,             -200,\n             -310,              121,\n               73,                7,\n              237,             -226,\n              139,             -456,\n              397,               35,\n                3,             -108,\n              323,              -75,\n              332,              198,\n              -99,              -21\n};\n\nconst SKP_Silk_NLSF_CBS SKP_Silk_NLSF_CB1_10_Stage_info[ NLSF_MSVQ_CB1_10_STAGES ] =\n{\n        {  32, &SKP_Silk_NLSF_MSVQ_CB1_10_Q15[ 10 *   0 ], &SKP_Silk_NLSF_MSVQ_CB1_10_rates_Q5[   0 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_10_Q15[ 10 *  32 ], &SKP_Silk_NLSF_MSVQ_CB1_10_rates_Q5[  32 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_10_Q15[ 10 *  40 ], &SKP_Silk_NLSF_MSVQ_CB1_10_rates_Q5[  40 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_10_Q15[ 10 *  48 ], &SKP_Silk_NLSF_MSVQ_CB1_10_rates_Q5[  48 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_10_Q15[ 10 *  56 ], &SKP_Silk_NLSF_MSVQ_CB1_10_rates_Q5[  56 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_10_Q15[ 10 *  64 ], &SKP_Silk_NLSF_MSVQ_CB1_10_rates_Q5[  64 ] }\n};\n\nconst SKP_Silk_NLSF_CB_struct SKP_Silk_NLSF_CB1_10 =\n{\n        NLSF_MSVQ_CB1_10_STAGES,\n        SKP_Silk_NLSF_CB1_10_Stage_info,\n        SKP_Silk_NLSF_MSVQ_CB1_10_ndelta_min_Q15,\n        SKP_Silk_NLSF_MSVQ_CB1_10_CDF,\n        SKP_Silk_NLSF_MSVQ_CB1_10_CDF_start_ptr,\n        SKP_Silk_NLSF_MSVQ_CB1_10_CDF_middle_idx\n};\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_tables_NLSF_CB1_16.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/**********************************************/\n/* This file has been automatically generated */\n/*                                            */\n/* ROM usage:  0.29 + 3.57 kB                 */\n/**********************************************/\n\n#include \"SKP_Silk_structs.h\"\n#include \"SKP_Silk_tables_NLSF_CB1_16.h\"\n#include \"SKP_Silk_tables.h\"\n\nconst SKP_uint16 SKP_Silk_NLSF_MSVQ_CB1_16_CDF[ NLSF_MSVQ_CB1_16_VECTORS + NLSF_MSVQ_CB1_16_STAGES ] =\n{\n            0,\n        19099,\n        26957,\n        30639,\n        34242,\n        37546,\n        40447,\n        43287,\n        46005,\n        48445,\n        49865,\n        51284,\n        52673,\n        53975,\n        55221,\n        56441,\n        57267,\n        58025,\n        58648,\n        59232,\n        59768,\n        60248,\n        60729,\n        61210,\n        61690,\n        62171,\n        62651,\n        63132,\n        63613,\n        64093,\n        64574,\n        65054,\n        65535,\n            0,\n        28808,\n        38775,\n        46801,\n        51785,\n        55886,\n        59410,\n        62572,\n        65535,\n            0,\n        27376,\n        38639,\n        45052,\n        51465,\n        55448,\n        59021,\n        62594,\n        65535,\n            0,\n        33403,\n        39569,\n        45102,\n        49961,\n        54047,\n        57959,\n        61788,\n        65535,\n            0,\n        25851,\n        43356,\n        47828,\n        52204,\n        55964,\n        59413,\n        62507,\n        65535,\n            0,\n        34277,\n        40337,\n        45432,\n        50311,\n        54326,\n        58171,\n        61853,\n        65535,\n            0,\n        33538,\n        39865,\n        45302,\n        50076,\n        54549,\n        58478,\n        62159,\n        65535,\n            0,\n        27445,\n        35258,\n        40665,\n        46072,\n        51362,\n        56540,\n        61086,\n        65535,\n            0,\n        22080,\n        30779,\n        37065,\n        43085,\n        48849,\n        54613,\n        60133,\n        65535,\n            0,\n        13417,\n        21748,\n        30078,\n        38231,\n        46383,\n        53091,\n        59515,\n        65535\n};\n\nconst SKP_uint16 * const SKP_Silk_NLSF_MSVQ_CB1_16_CDF_start_ptr[ NLSF_MSVQ_CB1_16_STAGES ] =\n{\n     &SKP_Silk_NLSF_MSVQ_CB1_16_CDF[   0 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_16_CDF[  33 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_16_CDF[  42 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_16_CDF[  51 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_16_CDF[  60 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_16_CDF[  69 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_16_CDF[  78 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_16_CDF[  87 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_16_CDF[  96 ],\n     &SKP_Silk_NLSF_MSVQ_CB1_16_CDF[ 105 ]\n};\n\nconst SKP_int SKP_Silk_NLSF_MSVQ_CB1_16_CDF_middle_idx[ NLSF_MSVQ_CB1_16_STAGES ] =\n{\n       5,\n       2,\n       2,\n       2,\n       2,\n       2,\n       2,\n       3,\n       3,\n       4\n};\n\nconst SKP_int16 SKP_Silk_NLSF_MSVQ_CB1_16_rates_Q5[ NLSF_MSVQ_CB1_16_VECTORS ] =\n{\n               57,               98,\n              133,              134,\n              138,              144,\n              145,              147,\n              152,              177,\n              177,              178,\n              181,              183,\n              184,              202,\n              206,              215,\n              218,              222,\n              227,              227,\n              227,              227,\n              227,              227,\n              227,              227,\n              227,              227,\n              227,              227,\n               38,               87,\n               97,              119,\n              128,              135,\n              140,              143,\n               40,               81,\n              107,              107,\n              129,              134,\n              134,              143,\n               31,              109,\n              114,              120,\n              128,              130,\n              131,              132,\n               43,               61,\n              124,              125,\n              132,              136,\n              141,              142,\n               30,              110,\n              118,              120,\n              129,              131,\n              133,              133,\n               31,              108,\n              115,              121,\n              124,              130,\n              133,              137,\n               40,               98,\n              115,              115,\n              116,              117,\n              123,              124,\n               50,               93,\n              108,              110,\n              112,              112,\n              114,              115,\n               73,               95,\n               95,               96,\n               96,              105,\n              107,              110\n};\n\nconst SKP_int SKP_Silk_NLSF_MSVQ_CB1_16_ndelta_min_Q15[ 16 + 1 ] =\n{\n              148,\n                3,\n               60,\n               68,\n              117,\n               86,\n              121,\n              124,\n              152,\n              153,\n              207,\n              151,\n              225,\n              239,\n              126,\n              183,\n              792\n};\n\nconst SKP_int16 SKP_Silk_NLSF_MSVQ_CB1_16_Q15[ 16 * NLSF_MSVQ_CB1_16_VECTORS ] =\n{\n             1309,             3060,             5071,             6996,\n             9028,            10938,            12934,            14891,\n            16933,            18854,            20792,            22764,\n            24753,            26659,            28626,            30501,\n             1264,             2745,             4610,             6408,\n             8286,            10043,            12084,            14108,\n            16118,            18163,            20095,            22164,\n            24264,            26316,            28329,            30251,\n             1044,             2080,             3672,             5179,\n             7140,             9100,            11070,            13065,\n            15423,            17790,            19931,            22101,\n            24290,            26361,            28499,            30418,\n             1131,             2476,             4478,             6149,\n             7902,             9875,            11938,            13809,\n            15869,            17730,            19948,            21707,\n            23761,            25535,            27426,            28917,\n             1040,             2004,             4026,             6100,\n             8432,            10494,            12610,            14694,\n            16797,            18775,            20799,            22782,\n            24772,            26682,            28631,            30516,\n             2310,             3812,             5913,             7933,\n            10033,            11881,            13885,            15798,\n            17751,            19576,            21482,            23276,\n            25157,            27010,            28833,            30623,\n             1254,             2847,             5013,             6781,\n             8626,            10370,            12726,            14633,\n            16281,            17852,            19870,            21472,\n            23002,            24629,            26710,            27960,\n             1468,             3059,             4987,             7026,\n             8741,            10412,            12281,            14020,\n            15970,            17723,            19640,            21522,\n            23472,            25661,            27986,            30225,\n             2171,             3566,             5605,             7384,\n             9404,            11220,            13030,            14758,\n            16687,            18417,            20346,            22091,\n            24055,            26212,            28356,            30397,\n             2409,             4676,             7543,             9786,\n            11419,            12935,            14368,            15653,\n            17366,            18943,            20762,            22477,\n            24440,            26327,            28284,            30242,\n             2354,             4222,             6820,             9107,\n            11596,            13934,            15973,            17682,\n            19158,            20517,            21991,            23420,\n            25178,            26936,            28794,            30527,\n             1323,             2414,             4184,             6039,\n             7534,             9398,            11099,            13097,\n            14799,            16451,            18434,            20887,\n            23490,            25838,            28046,            30225,\n             1361,             3243,             6048,             8511,\n            11001,            13145,            15073,            16608,\n            18126,            19381,            20912,            22607,\n            24660,            26668,            28663,            30566,\n             1216,             2648,             5901,             8422,\n            10037,            11425,            12973,            14603,\n            16686,            18600,            20555,            22415,\n            24450,            26280,            28206,            30077,\n             2417,             4048,             6316,             8433,\n            10510,            12757,            15072,            17295,\n            19573,            21503,            23329,            24782,\n            26235,            27689,            29214,            30819,\n             1012,             2345,             4991,             7377,\n             9465,            11916,            14296,            16566,\n            18672,            20544,            22292,            23838,\n            25415,            27050,            28848,            30551,\n             1937,             3693,             6267,             8019,\n            10372,            12194,            14287,            15657,\n            17431,            18864,            20769,            22206,\n            24037,            25463,            27383,            28602,\n             1969,             3305,             5017,             6726,\n             8375,             9993,            11634,            13280,\n            15078,            16751,            18464,            20119,\n            21959,            23858,            26224,            29298,\n             1198,             2647,             5428,             7423,\n             9775,            12155,            14665,            16344,\n            18121,            19790,            21557,            22847,\n            24484,            25742,            27639,            28711,\n             1636,             3353,             5447,             7597,\n             9837,            11647,            13964,            16019,\n            17862,            20116,            22319,            24037,\n            25966,            28086,            29914,            31294,\n             2676,             4105,             6378,             8223,\n            10058,            11549,            13072,            14453,\n            15956,            17355,            18931,            20402,\n            22183,            23884,            25717,            27723,\n             1373,             2593,             4449,             5633,\n             7300,             8425,             9474,            10818,\n            12769,            15722,            19002,            21429,\n            23682,            25924,            28135,            30333,\n             1596,             3183,             5378,             7164,\n             8670,            10105,            11470,            12834,\n            13991,            15042,            16642,            17903,\n            20759,            25283,            27770,            30240,\n             2037,             3987,             6237,             8117,\n             9954,            12245,            14217,            15892,\n            17775,            20114,            22314,            25942,\n            26305,            26483,            26796,            28561,\n             2181,             3858,             5760,             7924,\n            10041,            11577,            13769,            15700,\n            17429,            19879,            23583,            24538,\n            25212,            25693,            28688,            30507,\n             1992,             3882,             6474,             7883,\n             9381,            12672,            14340,            15701,\n            16658,            17832,            20850,            22885,\n            24677,            26457,            28491,            30460,\n             2391,             3988,             5448,             7432,\n            11014,            12579,            13140,            14146,\n            15898,            18592,            21104,            22993,\n            24673,            27186,            28142,            29612,\n             1713,             5102,             6989,             7798,\n             8670,            10110,            12746,            14881,\n            16709,            18407,            20126,            22107,\n            24181,            26198,            28237,            30137,\n             1612,             3617,             6148,             8359,\n             9576,            11528,            14936,            17809,\n            18287,            18729,            19001,            21111,\n            24631,            26596,            28740,            30643,\n             2266,             4168,             7862,             9546,\n             9618,             9703,            10134,            13897,\n            16265,            18432,            20587,            22605,\n            24754,            26994,            29125,            30840,\n             1840,             3917,             6272,             7809,\n             9714,            11438,            13767,            15799,\n            19244,            21972,            22980,            23180,\n            23723,            25650,            29117,            31085,\n             1458,             3612,             6008,             7488,\n             9827,            11893,            14086,            15734,\n            17440,            19535,            22424,            24767,\n            29246,            29928,            30516,            30947,\n             -102,             -121,              -31,               -6,\n                5,               -2,                8,              -18,\n               -4,                6,               14,               -2,\n              -12,              -16,              -12,              -60,\n             -126,             -353,             -574,             -677,\n             -657,             -617,             -498,             -393,\n             -348,             -277,             -225,             -164,\n             -102,              -70,              -31,               33,\n                4,              379,              387,              551,\n              605,              620,              532,              482,\n              442,              454,              385,              347,\n              322,              299,              266,              200,\n             1168,              951,              672,              246,\n               60,             -161,             -259,             -234,\n             -253,             -282,             -203,             -187,\n             -155,             -176,             -198,             -178,\n               10,              170,              393,              609,\n              555,              208,             -330,             -571,\n             -769,             -633,             -319,              -43,\n               95,              105,              106,              116,\n             -152,             -140,             -125,                5,\n              173,              274,              264,              331,\n              -37,             -293,             -609,             -786,\n             -959,             -814,             -645,             -238,\n              -91,               36,              -11,             -101,\n             -279,             -227,              -40,               90,\n              530,              677,              890,             1104,\n              999,              835,              564,              295,\n             -280,             -364,             -340,             -331,\n             -284,              288,              761,              880,\n              988,              627,              146,             -226,\n             -203,             -181,             -142,               39,\n               24,              -26,             -107,              -92,\n             -161,             -135,             -131,              -88,\n             -160,             -156,              -75,              -43,\n              -36,               -6,              -33,               33,\n             -324,             -415,             -108,              124,\n              157,              191,              203,              197,\n              144,              109,              152,              176,\n              190,              122,              101,              159,\n              663,              668,              480,              400,\n              379,              444,              446,              458,\n              343,              351,              310,              228,\n              133,               44,               75,               63,\n              -84,               39,              -29,               35,\n              -94,             -233,             -261,             -354,\n               77,              262,              -24,             -145,\n             -333,             -409,             -404,             -597,\n             -488,             -300,              910,              592,\n              412,              120,              130,              -51,\n              -37,              -77,             -172,             -181,\n             -159,             -148,              -72,              -62,\n              510,              516,              113,             -585,\n            -1075,             -957,             -417,             -195,\n                9,                7,              -88,             -173,\n              -91,               54,               98,               95,\n              -28,              197,             -527,             -621,\n              157,              122,             -168,              147,\n              309,              300,              336,              315,\n              396,              408,              376,              106,\n             -162,             -170,             -315,               98,\n              821,              908,              570,              -33,\n             -312,             -568,             -572,             -378,\n             -107,               23,              156,               93,\n             -129,              -87,               20,              -72,\n              -37,               40,               21,               27,\n               48,               75,               77,               65,\n               46,               71,               66,               47,\n              136,              344,              236,              322,\n              170,              283,              269,              291,\n              162,              -43,             -204,             -259,\n             -240,             -305,             -350,             -312,\n              447,              348,              345,              257,\n               71,             -131,              -77,             -190,\n             -202,              -40,               35,              133,\n              261,              365,              438,              303,\n               -8,               22,              140,              137,\n             -300,             -641,             -764,             -268,\n              -23,              -25,               73,             -162,\n             -150,             -212,              -72,                6,\n               39,               78,              104,              -93,\n             -308,             -136,              117,              -71,\n             -513,             -820,             -700,             -450,\n             -161,              -23,               29,               78,\n              337,              106,             -406,             -782,\n             -112,              233,              383,               62,\n             -126,                6,              -77,              -29,\n             -146,             -123,              -51,              -27,\n              -27,             -381,             -641,              402,\n              539,                8,             -207,             -366,\n              -36,              -27,             -204,             -227,\n             -237,             -189,              -64,               51,\n              -92,             -137,             -281,               62,\n              233,               92,              148,              294,\n              363,              416,              564,              625,\n              370,              -36,             -469,             -462,\n              102,              168,               32,              117,\n              -21,               97,              139,               89,\n              104,               35,                4,               82,\n               66,               58,               73,               93,\n              -76,             -320,             -236,             -189,\n             -203,             -142,              -27,              -73,\n                9,               -9,              -25,               12,\n              -15,                4,                4,              -50,\n              314,              180,              162,              -49,\n              199,             -108,             -227,              -66,\n             -447,              -67,             -264,             -394,\n                5,               55,             -133,             -176,\n             -116,             -241,              272,              109,\n              282,              262,              192,              -64,\n             -392,             -514,              156,              203,\n              154,               72,              -34,             -160,\n              -73,                3,              -33,             -431,\n              321,               18,             -567,             -590,\n             -108,               88,               66,               51,\n              -31,             -193,              -46,               65,\n              -29,              -23,              215,              -31,\n              101,             -113,               32,              304,\n               88,              320,              448,                5,\n             -439,             -562,             -508,             -135,\n              -13,             -171,               -8,              182,\n              -99,             -181,             -149,              376,\n              476,               64,             -396,             -652,\n             -150,              176,              222,               65,\n             -590,              719,              271,              399,\n              245,               72,             -156,             -152,\n             -176,               59,               94,              125,\n               -9,               -7,                9,                1,\n              -61,             -116,              -82,                1,\n               79,               22,              -44,              -15,\n              -48,              -65,              -62,             -101,\n             -102,              -54,              -70,              -78,\n              -80,              -25,              398,               71,\n              139,               38,               90,              194,\n              222,              249,              165,               94,\n              221,              262,              163,               91,\n             -206,              573,              200,             -287,\n             -147,                5,              -18,              -85,\n              -74,             -125,              -87,               85,\n              141,                4,               -4,               28,\n              234,               48,             -150,             -111,\n             -506,              237,             -209,              345,\n               94,             -124,               77,              121,\n              143,               12,              -80,              -48,\n              191,              144,              -93,              -65,\n             -151,             -643,              435,              106,\n               87,                7,               65,              102,\n               94,               68,                5,               99,\n              222,               93,               94,              355,\n              -13,              -89,             -228,             -503,\n              287,              109,              108,              449,\n              253,              -29,             -109,             -116,\n               15,              -73,              -20,              131,\n             -147,               72,               59,             -150,\n             -594,              273,              316,              132,\n              199,              106,              198,              212,\n              220,               82,               45,              -13,\n              223,              137,              270,               38,\n              252,              135,             -177,             -207,\n             -360,             -102,              403,              406,\n              -14,               83,               64,               51,\n               -7,              -99,              -97,              -88,\n             -124,              -65,               42,               32,\n               28,               29,               12,               20,\n              119,              -26,             -212,             -201,\n              373,              251,              141,              103,\n               36,              -52,               66,               18,\n               -6,              -95,             -196,                5,\n               98,              -85,             -108,              218,\n             -164,               20,              356,              172,\n               37,              266,               23,              112,\n              -24,              -99,              -92,             -178,\n               29,             -278,              388,              -60,\n             -220,              300,              -13,              154,\n              191,               15,              -37,             -110,\n             -153,             -150,             -114,               -7,\n              -94,              -31,              -62,             -177,\n                4,              -70,               35,              453,\n              147,             -247,             -328,              101,\n               20,             -114,              147,              108,\n             -119,             -109,             -102,             -238,\n               55,             -102,              173,              -89,\n              129,              138,             -330,             -160,\n              485,              154,              -59,             -170,\n              -20,              -34,             -261,              -40,\n             -129,               77,              -84,               69,\n               83,              160,              169,               63,\n             -516,               30,              336,               52,\n               -0,              -52,             -124,              158,\n               19,              197,              -10,             -375,\n              405,              285,              114,             -395,\n              -47,              196,               62,               87,\n             -106,              -65,              -75,              -69,\n              -13,               34,               99,               59,\n               83,               98,               44,                0,\n               24,               18,               17,               70,\n              -22,              194,              208,              144,\n              -79,              -15,               32,             -104,\n              -28,             -105,             -186,             -212,\n             -228,              -79,              -76,               51,\n              -71,               72,              118,              -34,\n               -3,             -171,                5,                2,\n             -108,             -125,               62,              -58,\n               58,             -121,               73,             -466,\n               92,               63,              -94,              -78,\n              -76,              212,               36,             -225,\n              -71,             -354,              152,              143,\n              -79,             -246,              -51,              -31,\n               -6,             -270,              240,              210,\n               30,             -157,             -231,               74,\n             -146,               88,             -273,              156,\n               92,               56,               71,                2,\n              318,              164,               32,             -110,\n              -35,              -41,              -95,             -106,\n               11,              132,              -68,               55,\n              123,              -83,             -149,              212,\n              132,                0,             -194,               55,\n              206,             -108,             -353,              289,\n             -195,                1,              233,              -22,\n              -60,               20,               26,               68,\n              166,               27,              -58,              130,\n              112,              107,               27,             -165,\n              115,              -93,              -37,               38,\n               83,              483,               65,             -229,\n              -13,              157,               85,               50,\n              136,               10,               32,               83,\n               82,               55,                5,               -9,\n              -52,              -78,              -81,              -51,\n               40,               18,             -127,             -224,\n              -41,               53,             -210,             -113,\n               24,              -17,             -187,              -89,\n                8,              121,               83,               77,\n               91,              -74,              -35,             -112,\n             -161,             -173,              102,              132,\n             -125,              -61,              103,             -260,\n               52,              166,              -32,             -156,\n              -87,              -56,               60,              -70,\n             -124,              242,              114,             -251,\n             -166,              201,              127,               28,\n              -11,               23,              -80,             -115,\n              -20,              -51,             -348,              340,\n              -34,              133,               13,               92,\n             -124,             -136,             -120,              -26,\n               -6,               17,               28,               21,\n              120,             -168,              160,              -35,\n              115,               28,                9,                7,\n              -56,               39,              156,              256,\n              -18,                1,              277,               82,\n              -70,             -144,              -88,              -13,\n              -59,             -157,                8,             -134,\n               21,              -40,               58,              -21,\n              194,             -276,               97,              279,\n              -56,             -140,              125,               57,\n             -184,             -204,              -70,               -2,\n              128,             -202,              -78,              230,\n              -23,              161,             -102,                1,\n                1,              180,              -31,              -86,\n             -167,              -57,              -60,               27,\n              -13,               99,              108,              111,\n               76,               69,               34,              -21,\n               53,               38,               34,               78,\n               73,              219,               51,               15,\n              -72,             -103,             -207,               30,\n              213,              -14,               31,              -94,\n              -40,             -144,               67,                4,\n              105,               59,             -240,               25,\n              244,               69,               58,               23,\n              -24,               -5,              -15,             -133,\n              -71,              -67,              181,               29,\n              -45,              121,               96,               51,\n              -72,              -53,               56,             -153,\n              -27,               85,              183,              211,\n              105,              -34,              -46,               43,\n              -72,              -93,               36,             -128,\n               29,              111,              -95,             -156,\n             -179,             -235,               21,              -39,\n              -71,              -33,              -61,             -252,\n              230,             -131,              157,              -21,\n              -85,              -28,             -123,               80,\n             -160,               63,               47,               -6,\n              -49,              -96,              -19,               17,\n              -58,               17,               -0,              -13,\n             -170,               25,              -35,               59,\n               10,              -31,             -413,               81,\n               62,               18,             -164,              245,\n               92,             -165,               42,               26,\n              126,             -248,              193,              -55,\n               16,               39,               14,               50\n};\n\nconst SKP_Silk_NLSF_CBS SKP_Silk_NLSF_CB1_16_Stage_info[ NLSF_MSVQ_CB1_16_STAGES ] =\n{\n        {  32, &SKP_Silk_NLSF_MSVQ_CB1_16_Q15[ 16 *   0 ], &SKP_Silk_NLSF_MSVQ_CB1_16_rates_Q5[   0 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_16_Q15[ 16 *  32 ], &SKP_Silk_NLSF_MSVQ_CB1_16_rates_Q5[  32 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_16_Q15[ 16 *  40 ], &SKP_Silk_NLSF_MSVQ_CB1_16_rates_Q5[  40 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_16_Q15[ 16 *  48 ], &SKP_Silk_NLSF_MSVQ_CB1_16_rates_Q5[  48 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_16_Q15[ 16 *  56 ], &SKP_Silk_NLSF_MSVQ_CB1_16_rates_Q5[  56 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_16_Q15[ 16 *  64 ], &SKP_Silk_NLSF_MSVQ_CB1_16_rates_Q5[  64 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_16_Q15[ 16 *  72 ], &SKP_Silk_NLSF_MSVQ_CB1_16_rates_Q5[  72 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_16_Q15[ 16 *  80 ], &SKP_Silk_NLSF_MSVQ_CB1_16_rates_Q5[  80 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_16_Q15[ 16 *  88 ], &SKP_Silk_NLSF_MSVQ_CB1_16_rates_Q5[  88 ] },\n        {   8, &SKP_Silk_NLSF_MSVQ_CB1_16_Q15[ 16 *  96 ], &SKP_Silk_NLSF_MSVQ_CB1_16_rates_Q5[  96 ] }\n};\n\nconst SKP_Silk_NLSF_CB_struct SKP_Silk_NLSF_CB1_16 =\n{\n        NLSF_MSVQ_CB1_16_STAGES,\n        SKP_Silk_NLSF_CB1_16_Stage_info,\n        SKP_Silk_NLSF_MSVQ_CB1_16_ndelta_min_Q15,\n        SKP_Silk_NLSF_MSVQ_CB1_16_CDF,\n        SKP_Silk_NLSF_MSVQ_CB1_16_CDF_start_ptr,\n        SKP_Silk_NLSF_MSVQ_CB1_16_CDF_middle_idx\n};\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_tables_gain.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_tables.h\"\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\nconst SKP_uint16 SKP_Silk_gain_CDF[ 2 ][ 65 ] = \n{\n{\n         0,     18,     45,     94,    181,    320,    519,    777,\n      1093,   1468,   1909,   2417,   2997,   3657,   4404,   5245,\n      6185,   7228,   8384,   9664,  11069,  12596,  14244,  16022,\n     17937,  19979,  22121,  24345,  26646,  29021,  31454,  33927,\n     36438,  38982,  41538,  44068,  46532,  48904,  51160,  53265,\n     55184,  56904,  58422,  59739,  60858,  61793,  62568,  63210,\n     63738,  64165,  64504,  64769,  64976,  65133,  65249,  65330,\n     65386,  65424,  65451,  65471,  65487,  65501,  65513,  65524,\n     65535\n},\n{\n         0,    214,    581,   1261,   2376,   3920,   5742,   7632,\n      9449,  11157,  12780,  14352,  15897,  17427,  18949,  20462,\n     21957,  23430,  24889,  26342,  27780,  29191,  30575,  31952,\n     33345,  34763,  36200,  37642,  39083,  40519,  41930,  43291,\n     44602,  45885,  47154,  48402,  49619,  50805,  51959,  53069,\n     54127,  55140,  56128,  57101,  58056,  58979,  59859,  60692,\n     61468,  62177,  62812,  63368,  63845,  64242,  64563,  64818,\n     65023,  65184,  65306,  65391,  65447,  65482,  65505,  65521,\n     65535\n}\n};\n\nconst SKP_int SKP_Silk_gain_CDF_offset = 32;\n\n\nconst SKP_uint16 SKP_Silk_delta_gain_CDF[ 46 ] = {\n         0,   2358,   3856,   7023,  15376,  53058,  59135,  61555,\n     62784,  63498,  63949,  64265,  64478,  64647,  64783,  64894,\n     64986,  65052,  65113,  65169,  65213,  65252,  65284,  65314,\n     65338,  65359,  65377,  65392,  65403,  65415,  65424,  65432,\n     65440,  65448,  65455,  65462,  65470,  65477,  65484,  65491,\n     65499,  65506,  65513,  65521,  65528,  65535\n};\n\nconst SKP_int SKP_Silk_delta_gain_CDF_offset = 5;\n\n#ifdef __cplusplus\n}\n#endif\n"
  },
  {
    "path": "app/jni/SKP_Silk_tables_other.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_structs.h\"\n#include \"SKP_Silk_define.h\"\n#include \"SKP_Silk_tables.h\"\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n/* Piece-wise linear mapping from bitrate in kbps to coding quality in dB SNR */\nconst SKP_int32 TargetRate_table_NB[ TARGET_RATE_TAB_SZ ] = {\n    0,      8000,   9000,   11000,  13000,  16000,  22000,  MAX_TARGET_RATE_BPS\n};\nconst SKP_int32 TargetRate_table_MB[ TARGET_RATE_TAB_SZ ] = {\n    0,      10000,  12000,  14000,  17000,  21000,  28000,  MAX_TARGET_RATE_BPS\n};\nconst SKP_int32 TargetRate_table_WB[ TARGET_RATE_TAB_SZ ] = {\n    0,      11000,  14000,  17000,  21000,  26000,  36000,  MAX_TARGET_RATE_BPS\n};\nconst SKP_int32 TargetRate_table_SWB[ TARGET_RATE_TAB_SZ ] = {\n    0,      13000,  16000,  19000,  25000,  32000,  46000,  MAX_TARGET_RATE_BPS\n};\nconst SKP_int32 SNR_table_Q1[ TARGET_RATE_TAB_SZ ] = {\n    19,     31,     35,     39,     43,     47,     54,     64\n};\n\nconst SKP_int32 SNR_table_one_bit_per_sample_Q7[ 4 ] = {\n    1984,   2240,   2408,   2708\n};\n\n/* Filter coeficicnts for HP filter: 4. Order filter implementad as two biquad filters  */\nconst SKP_int16 SKP_Silk_SWB_detect_B_HP_Q13[ NB_SOS ][ 3 ] = {\n    //{400, -550, 400}, {400, 130, 400}, {400, 390, 400}\n    {575, -948, 575}, {575, -221, 575}, {575, 104, 575} \n};\nconst SKP_int16 SKP_Silk_SWB_detect_A_HP_Q13[ NB_SOS ][ 2 ] = {\n    {14613, 6868}, {12883, 7337}, {11586, 7911}\n    //{14880, 6900}, {14400, 7300}, {13700, 7800}\n};\n\n/* Decoder high-pass filter coefficients for 24 kHz sampling, -6 dB @ 44 Hz */\nconst SKP_int16 SKP_Silk_Dec_A_HP_24[ DEC_HP_ORDER     ] = {-16220, 8030};              // second order AR coefs, Q13\nconst SKP_int16 SKP_Silk_Dec_B_HP_24[ DEC_HP_ORDER + 1 ] = {8000, -16000, 8000};        // second order MA coefs, Q13\n\n/* Decoder high-pass filter coefficients for 16 kHz sampling, - 6 dB @ 46 Hz */\nconst SKP_int16 SKP_Silk_Dec_A_HP_16[ DEC_HP_ORDER     ] = {-16127, 7940};              // second order AR coefs, Q13\nconst SKP_int16 SKP_Silk_Dec_B_HP_16[ DEC_HP_ORDER + 1 ] = {8000, -16000, 8000};        // second order MA coefs, Q13\n\n/* Decoder high-pass filter coefficients for 12 kHz sampling, -6 dB @ 44 Hz */\nconst SKP_int16 SKP_Silk_Dec_A_HP_12[ DEC_HP_ORDER     ] = {-16043, 7859};              // second order AR coefs, Q13\nconst SKP_int16 SKP_Silk_Dec_B_HP_12[ DEC_HP_ORDER + 1 ] = {8000, -16000, 8000};        // second order MA coefs, Q13\n\n/* Decoder high-pass filter coefficients for 8 kHz sampling, -6 dB @ 43 Hz */\nconst SKP_int16 SKP_Silk_Dec_A_HP_8[ DEC_HP_ORDER     ] = {-15885, 7710};               // second order AR coefs, Q13\nconst SKP_int16 SKP_Silk_Dec_B_HP_8[ DEC_HP_ORDER + 1 ] = {8000, -16000, 8000};         // second order MA coefs, Q13\n\n/* table for LSB coding */\nconst SKP_uint16 SKP_Silk_lsb_CDF[ 3 ] = {0,  40000,  65535};\n\n/* tables for LTPScale */\nconst SKP_uint16 SKP_Silk_LTPscale_CDF[ 4 ] = {0,  32000,  48000,  65535};\nconst SKP_int    SKP_Silk_LTPscale_offset   = 2;\n\n/* tables for VAD flag */\nconst SKP_uint16 SKP_Silk_vadflag_CDF[ 3 ] = {0,  22000,  65535}; // 66% for speech, 33% for no speech\nconst SKP_int    SKP_Silk_vadflag_offset   = 1;\n\n/* tables for sampling rate */\nconst SKP_int    SKP_Silk_SamplingRates_table[ 4 ] = {8, 12, 16, 24};\nconst SKP_uint16 SKP_Silk_SamplingRates_CDF[ 5 ]   = {0,  16000,  32000,  48000,  65535};\nconst SKP_int    SKP_Silk_SamplingRates_offset     = 2;\n\n/* tables for NLSF interpolation factor */\nconst SKP_uint16 SKP_Silk_NLSF_interpolation_factor_CDF[ 6 ] = {0,   3706,   8703,  19226,  30926,  65535};\nconst SKP_int    SKP_Silk_NLSF_interpolation_factor_offset   = 4;\n\n/* Table for frame termination indication */\nconst SKP_uint16 SKP_Silk_FrameTermination_CDF[ 5 ] = {0, 20000, 45000, 56000, 65535};\nconst SKP_int    SKP_Silk_FrameTermination_offset   = 2;\n\n/* Table for random seed */\nconst SKP_uint16 SKP_Silk_Seed_CDF[ 5 ] = {0, 16384, 32768, 49152, 65535};\nconst SKP_int    SKP_Silk_Seed_offset   = 2;\n\n/* Quantization offsets */\nconst SKP_int16  SKP_Silk_Quantization_Offsets_Q10[ 2 ][ 2 ] = {\n    { OFFSET_VL_Q10, OFFSET_VH_Q10 }, { OFFSET_UVL_Q10, OFFSET_UVH_Q10 }\n};\n\n/* Table for LTPScale */\nconst SKP_int16 SKP_Silk_LTPScales_table_Q14[ 3 ] = { 15565, 11469, 8192 };\n\n#if SWITCH_TRANSITION_FILTERING\n/*  Elliptic/Cauer filters designed with 0.1 dB passband ripple, \n        80 dB minimum stopband attenuation, and\n        [0.95 : 0.15 : 0.35] normalized cut off frequencies. */\n\n/* Interpolation points for filter coefficients used in the bandwidth transition smoother */\nconst SKP_int32 SKP_Silk_Transition_LP_B_Q28[ TRANSITION_INT_NUM ][ TRANSITION_NB ] = \n{\n{    250767114,  501534038,  250767114  },\n{    209867381,  419732057,  209867381  },\n{    170987846,  341967853,  170987846  },\n{    131531482,  263046905,  131531482  },\n{     89306658,  178584282,   89306658  }\n};\n\n/* Interpolation points for filter coefficients used in the bandwidth transition smoother */\nconst SKP_int32 SKP_Silk_Transition_LP_A_Q28[ TRANSITION_INT_NUM ][ TRANSITION_NA ] = \n{\n{    506393414,  239854379  },\n{    411067935,  169683996  },\n{    306733530,  116694253  },\n{    185807084,   77959395  },\n{     35497197,   57401098  }\n};\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_tables_pitch_lag.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_tables.h\"\n\nconst SKP_uint16 SKP_Silk_pitch_lag_NB_CDF[ 8 * ( PITCH_EST_MAX_LAG_MS - PITCH_EST_MIN_LAG_MS ) + 2 ] = {\n         0,    194,    395,    608,    841,   1099,   1391,   1724,\n      2105,   2544,   3047,   3624,   4282,   5027,   5865,   6799,\n      7833,   8965,  10193,  11510,  12910,  14379,  15905,  17473,\n     19065,  20664,  22252,  23814,  25335,  26802,  28206,  29541,\n     30803,  31992,  33110,  34163,  35156,  36098,  36997,  37861,\n     38698,  39515,  40319,  41115,  41906,  42696,  43485,  44273,\n     45061,  45847,  46630,  47406,  48175,  48933,  49679,  50411,\n     51126,  51824,  52502,  53161,  53799,  54416,  55011,  55584,\n     56136,  56666,  57174,  57661,  58126,  58570,  58993,  59394,\n     59775,  60134,  60472,  60790,  61087,  61363,  61620,  61856,\n     62075,  62275,  62458,  62625,  62778,  62918,  63045,  63162,\n     63269,  63368,  63459,  63544,  63623,  63698,  63769,  63836,\n     63901,  63963,  64023,  64081,  64138,  64194,  64248,  64301,\n     64354,  64406,  64457,  64508,  64558,  64608,  64657,  64706,\n     64754,  64803,  64851,  64899,  64946,  64994,  65041,  65088,\n     65135,  65181,  65227,  65272,  65317,  65361,  65405,  65449,\n     65492,  65535\n};\n\nconst SKP_int SKP_Silk_pitch_lag_NB_CDF_offset = 43;\n\nconst SKP_uint16 SKP_Silk_pitch_contour_NB_CDF[ 12 ] = {\n         0,  14445,  18587,  25628,  30013,  34859,  40597,  48426,\n     54460,  59033,  62990,  65535\n};\n\nconst SKP_int SKP_Silk_pitch_contour_NB_CDF_offset = 5;\n\nconst SKP_uint16 SKP_Silk_pitch_lag_MB_CDF[ 12 * ( PITCH_EST_MAX_LAG_MS - PITCH_EST_MIN_LAG_MS ) + 2 ] = {\n         0,    132,    266,    402,    542,    686,    838,    997,\n      1167,   1349,   1546,   1760,   1993,   2248,   2528,   2835,\n      3173,   3544,   3951,   4397,   4882,   5411,   5984,   6604,\n      7270,   7984,   8745,   9552,  10405,  11300,  12235,  13206,\n     14209,  15239,  16289,  17355,  18430,  19507,  20579,  21642,\n     22688,  23712,  24710,  25677,  26610,  27507,  28366,  29188,\n     29971,  30717,  31427,  32104,  32751,  33370,  33964,  34537,\n     35091,  35630,  36157,  36675,  37186,  37692,  38195,  38697,\n     39199,  39701,  40206,  40713,  41222,  41733,  42247,  42761,\n     43277,  43793,  44309,  44824,  45336,  45845,  46351,  46851,\n     47347,  47836,  48319,  48795,  49264,  49724,  50177,  50621,\n     51057,  51484,  51902,  52312,  52714,  53106,  53490,  53866,\n     54233,  54592,  54942,  55284,  55618,  55944,  56261,  56571,\n     56873,  57167,  57453,  57731,  58001,  58263,  58516,  58762,\n     58998,  59226,  59446,  59656,  59857,  60050,  60233,  60408,\n     60574,  60732,  60882,  61024,  61159,  61288,  61410,  61526,\n     61636,  61742,  61843,  61940,  62033,  62123,  62210,  62293,\n     62374,  62452,  62528,  62602,  62674,  62744,  62812,  62879,\n     62945,  63009,  63072,  63135,  63196,  63256,  63316,  63375,\n     63434,  63491,  63549,  63605,  63661,  63717,  63772,  63827,\n     63881,  63935,  63988,  64041,  64094,  64147,  64199,  64252,\n     64304,  64356,  64409,  64461,  64513,  64565,  64617,  64669,\n     64721,  64773,  64824,  64875,  64925,  64975,  65024,  65072,\n     65121,  65168,  65215,  65262,  65308,  65354,  65399,  65445,\n     65490,  65535\n};\n\nconst SKP_int SKP_Silk_pitch_lag_MB_CDF_offset = 64;\n\nconst SKP_uint16 SKP_Silk_pitch_lag_WB_CDF[ 16 * ( PITCH_EST_MAX_LAG_MS - PITCH_EST_MIN_LAG_MS ) + 2 ] = {\n         0,    106,    213,    321,    429,    539,    651,    766,\n       884,   1005,   1132,   1264,   1403,   1549,   1705,   1870,\n      2047,   2236,   2439,   2658,   2893,   3147,   3420,   3714,\n      4030,   4370,   4736,   5127,   5546,   5993,   6470,   6978,\n      7516,   8086,   8687,   9320,   9985,  10680,  11405,  12158,\n     12938,  13744,  14572,  15420,  16286,  17166,  18057,  18955,\n     19857,  20759,  21657,  22547,  23427,  24293,  25141,  25969,\n     26774,  27555,  28310,  29037,  29736,  30406,  31048,  31662,\n     32248,  32808,  33343,  33855,  34345,  34815,  35268,  35704,\n     36127,  36537,  36938,  37330,  37715,  38095,  38471,  38844,\n     39216,  39588,  39959,  40332,  40707,  41084,  41463,  41844,\n     42229,  42615,  43005,  43397,  43791,  44186,  44583,  44982,\n     45381,  45780,  46179,  46578,  46975,  47371,  47765,  48156,\n     48545,  48930,  49312,  49690,  50064,  50433,  50798,  51158,\n     51513,  51862,  52206,  52544,  52877,  53204,  53526,  53842,\n     54152,  54457,  54756,  55050,  55338,  55621,  55898,  56170,\n     56436,  56697,  56953,  57204,  57449,  57689,  57924,  58154,\n     58378,  58598,  58812,  59022,  59226,  59426,  59620,  59810,\n     59994,  60173,  60348,  60517,  60681,  60840,  60993,  61141,\n     61284,  61421,  61553,  61679,  61800,  61916,  62026,  62131,\n     62231,  62326,  62417,  62503,  62585,  62663,  62737,  62807,\n     62874,  62938,  62999,  63057,  63113,  63166,  63217,  63266,\n     63314,  63359,  63404,  63446,  63488,  63528,  63567,  63605,\n     63642,  63678,  63713,  63748,  63781,  63815,  63847,  63879,\n     63911,  63942,  63973,  64003,  64033,  64063,  64092,  64121,\n     64150,  64179,  64207,  64235,  64263,  64291,  64319,  64347,\n     64374,  64401,  64428,  64455,  64481,  64508,  64534,  64560,\n     64585,  64610,  64635,  64660,  64685,  64710,  64734,  64758,\n     64782,  64807,  64831,  64855,  64878,  64902,  64926,  64950,\n     64974,  64998,  65022,  65045,  65069,  65093,  65116,  65139,\n     65163,  65186,  65209,  65231,  65254,  65276,  65299,  65321,\n     65343,  65364,  65386,  65408,  65429,  65450,  65471,  65493,\n     65514,  65535\n};\n\nconst SKP_int SKP_Silk_pitch_lag_WB_CDF_offset = 86;\n\n\nconst SKP_uint16 SKP_Silk_pitch_lag_SWB_CDF[ 24 * ( PITCH_EST_MAX_LAG_MS - PITCH_EST_MIN_LAG_MS ) + 2 ] = {\n         0,    253,    505,    757,   1008,   1258,   1507,   1755,\n      2003,   2249,   2494,   2738,   2982,   3225,   3469,   3713,\n      3957,   4202,   4449,   4698,   4949,   5203,   5460,   5720,\n      5983,   6251,   6522,   6798,   7077,   7361,   7650,   7942,\n      8238,   8539,   8843,   9150,   9461,   9775,  10092,  10411,\n     10733,  11057,  11383,  11710,  12039,  12370,  12701,  13034,\n     13368,  13703,  14040,  14377,  14716,  15056,  15398,  15742,\n     16087,  16435,  16785,  17137,  17492,  17850,  18212,  18577,\n     18946,  19318,  19695,  20075,  20460,  20849,  21243,  21640,\n     22041,  22447,  22856,  23269,  23684,  24103,  24524,  24947,\n     25372,  25798,  26225,  26652,  27079,  27504,  27929,  28352,\n     28773,  29191,  29606,  30018,  30427,  30831,  31231,  31627,\n     32018,  32404,  32786,  33163,  33535,  33902,  34264,  34621,\n     34973,  35320,  35663,  36000,  36333,  36662,  36985,  37304,\n     37619,  37929,  38234,  38535,  38831,  39122,  39409,  39692,\n     39970,  40244,  40513,  40778,  41039,  41295,  41548,  41796,\n     42041,  42282,  42520,  42754,  42985,  43213,  43438,  43660,\n     43880,  44097,  44312,  44525,  44736,  44945,  45153,  45359,\n     45565,  45769,  45972,  46175,  46377,  46578,  46780,  46981,\n     47182,  47383,  47585,  47787,  47989,  48192,  48395,  48599,\n     48804,  49009,  49215,  49422,  49630,  49839,  50049,  50259,\n     50470,  50682,  50894,  51107,  51320,  51533,  51747,  51961,\n     52175,  52388,  52601,  52813,  53025,  53236,  53446,  53655,\n     53863,  54069,  54274,  54477,  54679,  54879,  55078,  55274,\n     55469,  55662,  55853,  56042,  56230,  56415,  56598,  56779,\n     56959,  57136,  57311,  57484,  57654,  57823,  57989,  58152,\n     58314,  58473,  58629,  58783,  58935,  59084,  59230,  59373,\n     59514,  59652,  59787,  59919,  60048,  60174,  60297,  60417,\n     60533,  60647,  60757,  60865,  60969,  61070,  61167,  61262,\n     61353,  61442,  61527,  61609,  61689,  61765,  61839,  61910,\n     61979,  62045,  62109,  62170,  62230,  62287,  62343,  62396,\n     62448,  62498,  62547,  62594,  62640,  62685,  62728,  62770,\n     62811,  62852,  62891,  62929,  62967,  63004,  63040,  63075,\n     63110,  63145,  63178,  63212,  63244,  63277,  63308,  63340,\n     63371,  63402,  63432,  63462,  63491,  63521,  63550,  63578,\n     63607,  63635,  63663,  63690,  63718,  63744,  63771,  63798,\n     63824,  63850,  63875,  63900,  63925,  63950,  63975,  63999,\n     64023,  64046,  64069,  64092,  64115,  64138,  64160,  64182,\n     64204,  64225,  64247,  64268,  64289,  64310,  64330,  64351,\n     64371,  64391,  64411,  64431,  64450,  64470,  64489,  64508,\n     64527,  64545,  64564,  64582,  64600,  64617,  64635,  64652,\n     64669,  64686,  64702,  64719,  64735,  64750,  64766,  64782,\n     64797,  64812,  64827,  64842,  64857,  64872,  64886,  64901,\n     64915,  64930,  64944,  64959,  64974,  64988,  65003,  65018,\n     65033,  65048,  65063,  65078,  65094,  65109,  65125,  65141,\n     65157,  65172,  65188,  65204,  65220,  65236,  65252,  65268,\n     65283,  65299,  65314,  65330,  65345,  65360,  65375,  65390,\n     65405,  65419,  65434,  65449,  65463,  65477,  65492,  65506,\n     65521,  65535\n};\n\nconst SKP_int SKP_Silk_pitch_lag_SWB_CDF_offset = 128;\n\n\nconst SKP_uint16 SKP_Silk_pitch_contour_CDF[ 35 ] = {\n         0,    372,    843,   1315,   1836,   2644,   3576,   4719,\n      6088,   7621,   9396,  11509,  14245,  17618,  20777,  24294,\n     27992,  33116,  40100,  44329,  47558,  50679,  53130,  55557,\n     57510,  59022,  60285,  61345,  62316,  63140,  63762,  64321,\n     64729,  65099,  65535\n};\n\nconst SKP_int SKP_Silk_pitch_contour_CDF_offset = 17;\n\nconst SKP_uint16 SKP_Silk_pitch_delta_CDF[23] = {\n         0,    343,    740,   1249,   1889,   2733,   3861,   5396,\n      7552,  10890,  16053,  24152,  30220,  34680,  37973,  40405,\n     42243,  43708,  44823,  45773,  46462,  47055,  65535\n};\n\nconst SKP_int SKP_Silk_pitch_delta_CDF_offset = 11;\n"
  },
  {
    "path": "app/jni/SKP_Silk_tables_pulses_per_block.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_tables.h\"\n\nconst SKP_int SKP_Silk_max_pulses_table[ 4 ] = {\n         6,      8,     12,     18\n};\n\nconst SKP_uint16 SKP_Silk_pulses_per_block_CDF[ 10 ][ 21 ] = \n{\n{\n         0,  47113,  61501,  64590,  65125,  65277,  65352,  65407,\n     65450,  65474,  65488,  65501,  65508,  65514,  65516,  65520,\n     65521,  65523,  65524,  65526,  65535\n},\n{\n         0,  26368,  47760,  58803,  63085,  64567,  65113,  65333,\n     65424,  65474,  65498,  65511,  65517,  65520,  65523,  65525,\n     65526,  65528,  65529,  65530,  65535\n},\n{\n         0,   9601,  28014,  45877,  57210,  62560,  64611,  65260,\n     65447,  65500,  65511,  65519,  65521,  65525,  65526,  65529,\n     65530,  65531,  65532,  65534,  65535\n},\n{\n         0,   3351,  12462,  25972,  39782,  50686,  57644,  61525,\n     63521,  64506,  65009,  65255,  65375,  65441,  65471,  65488,\n     65497,  65505,  65509,  65512,  65535\n},\n{\n         0,    488,   2944,   9295,  19712,  32160,  43976,  53121,\n     59144,  62518,  64213,  65016,  65346,  65470,  65511,  65515,\n     65525,  65529,  65531,  65534,  65535\n},\n{\n         0,  17013,  30405,  40812,  48142,  53466,  57166,  59845,\n     61650,  62873,  63684,  64223,  64575,  64811,  64959,  65051,\n     65111,  65143,  65165,  65183,  65535\n},\n{\n         0,   2994,   8323,  15845,  24196,  32300,  39340,  45140,\n     49813,  53474,  56349,  58518,  60167,  61397,  62313,  62969,\n     63410,  63715,  63906,  64056,  65535\n},\n{\n         0,     88,    721,   2795,   7542,  14888,  24420,  34593,\n     43912,  51484,  56962,  60558,  62760,  64037,  64716,  65069,\n     65262,  65358,  65398,  65420,  65535\n},\n{\n         0,    287,    789,   2064,   4398,   8174,  13534,  20151,\n     27347,  34533,  41295,  47242,  52070,  55772,  58458,  60381,\n     61679,  62533,  63109,  63519,  65535\n},\n{\n         0,      1,      3,     91,   4521,  14708,  28329,  41955,\n     52116,  58375,  61729,  63534,  64459,  64924,  65092,  65164,\n     65182,  65198,  65203,  65211,  65535\n}\n};\n\nconst SKP_int SKP_Silk_pulses_per_block_CDF_offset = 6;\n\n\nconst SKP_int16 SKP_Silk_pulses_per_block_BITS_Q6[ 9 ][ 20 ] = \n{\n{\n        30,    140,    282,    444,    560,    625,    654,    677,\n       731,    780,    787,    844,    859,    960,    896,   1024,\n       960,   1024,    960,    821\n},\n{\n        84,    103,    164,    252,    350,    442,    526,    607,\n       663,    731,    787,    859,    923,    923,    960,   1024,\n       960,   1024,   1024,    875\n},\n{\n       177,    117,    120,    162,    231,    320,    426,    541,\n       657,    803,    832,    960,    896,   1024,    923,   1024,\n      1024,   1024,    960,   1024\n},\n{\n       275,    182,    146,    144,    166,    207,    261,    322,\n       388,    450,    516,    582,    637,    710,    762,    821,\n       832,    896,    923,    734\n},\n{\n       452,    303,    216,    170,    153,    158,    182,    220,\n       274,    337,    406,    489,    579,    681,    896,    811,\n       896,    960,    923,   1024\n},\n{\n       125,    147,    170,    202,    232,    265,    295,    332,\n       368,    406,    443,    483,    520,    563,    606,    646,\n       704,    739,    757,    483\n},\n{\n       285,    232,    200,    190,    193,    206,    224,    244,\n       266,    289,    315,    340,    367,    394,    425,    462,\n       496,    539,    561,    350\n},\n{\n       611,    428,    319,    242,    202,    178,    172,    180,\n       199,    229,    268,    313,    364,    422,    482,    538,\n       603,    683,    739,    586\n},\n{\n       501,    450,    364,    308,    264,    231,    212,    204,\n       204,    210,    222,    241,    265,    295,    326,    362,\n       401,    437,    469,    321\n}\n};\n\nconst SKP_uint16 SKP_Silk_rate_levels_CDF[ 2 ][ 10 ] = \n{\n{\n         0,   2005,  12717,  20281,  31328,  36234,  45816,  57753,\n     63104,  65535\n},\n{\n         0,   8553,  23489,  36031,  46295,  53519,  56519,  59151,\n     64185,  65535\n}\n};\n\nconst SKP_int SKP_Silk_rate_levels_CDF_offset = 4;\n\n\nconst SKP_int16 SKP_Silk_rate_levels_BITS_Q6[ 2 ][ 9 ] = \n{\n{\n       322,    167,    199,    164,    239,    178,    157,    231,\n       304\n},\n{\n       188,    137,    153,    171,    204,    285,    297,    237,\n       358\n}\n};\n\nconst SKP_uint16 SKP_Silk_shell_code_table0[ 33 ] = {\n         0,  32748,  65535,      0,   9505,  56230,  65535,      0,\n      4093,  32204,  61720,  65535,      0,   2285,  16207,  48750,\n     63424,  65535,      0,   1709,   9446,  32026,  55752,  63876,\n     65535,      0,   1623,   6986,  21845,  45381,  59147,  64186,\n     65535\n};\n\nconst SKP_uint16 SKP_Silk_shell_code_table1[ 52 ] = {\n         0,  32691,  65535,      0,  12782,  52752,  65535,      0,\n      4847,  32665,  60899,  65535,      0,   2500,  17305,  47989,\n     63369,  65535,      0,   1843,  10329,  32419,  55433,  64277,\n     65535,      0,   1485,   7062,  21465,  43414,  59079,  64623,\n     65535,      0,      0,   4841,  14797,  31799,  49667,  61309,\n     65535,  65535,      0,      0,      0,   8032,  21695,  41078,\n     56317,  65535,  65535,  65535\n};\n\nconst SKP_uint16 SKP_Silk_shell_code_table2[ 102 ] = {\n         0,  32615,  65535,      0,  14447,  50912,  65535,      0,\n      6301,  32587,  59361,  65535,      0,   3038,  18640,  46809,\n     62852,  65535,      0,   1746,  10524,  32509,  55273,  64278,\n     65535,      0,   1234,   6360,  21259,  43712,  59651,  64805,\n     65535,      0,   1020,   4461,  14030,  32286,  51249,  61904,\n     65100,  65535,      0,    851,   3435,  10006,  23241,  40797,\n     55444,  63009,  65252,  65535,      0,      0,   2075,   7137,\n     17119,  31499,  46982,  58723,  63976,  65535,  65535,      0,\n         0,      0,   3820,  11572,  23038,  37789,  51969,  61243,\n     65535,  65535,  65535,      0,      0,      0,      0,   6882,\n     16828,  30444,  44844,  57365,  65535,  65535,  65535,  65535,\n         0,      0,      0,      0,      0,  10093,  22963,  38779,\n     54426,  65535,  65535,  65535,  65535,  65535\n};\n\nconst SKP_uint16 SKP_Silk_shell_code_table3[ 207 ] = {\n         0,  32324,  65535,      0,  15328,  49505,  65535,      0,\n      7474,  32344,  57955,  65535,      0,   3944,  19450,  45364,\n     61873,  65535,      0,   2338,  11698,  32435,  53915,  63734,\n     65535,      0,   1506,   7074,  21778,  42972,  58861,  64590,\n     65535,      0,   1027,   4490,  14383,  32264,  50980,  61712,\n     65043,  65535,      0,    760,   3022,   9696,  23264,  41465,\n     56181,  63253,  65251,  65535,      0,    579,   2256,   6873,\n     16661,  31951,  48250,  59403,  64198,  65360,  65535,      0,\n       464,   1783,   5181,  12269,  24247,  39877,  53490,  61502,\n     64591,  65410,  65535,      0,    366,   1332,   3880,   9273,\n     18585,  32014,  45928,  56659,  62616,  64899,  65483,  65535,\n         0,    286,   1065,   3089,   6969,  14148,  24859,  38274,\n     50715,  59078,  63448,  65091,  65481,  65535,      0,      0,\n       482,   2010,   5302,  10408,  18988,  30698,  43634,  54233,\n     60828,  64119,  65288,  65535,  65535,      0,      0,      0,\n      1006,   3531,   7857,  14832,  24543,  36272,  47547,  56883,\n     62327,  64746,  65535,  65535,  65535,      0,      0,      0,\n         0,   1863,   4950,  10730,  19284,  29397,  41382,  52335,\n     59755,  63834,  65535,  65535,  65535,  65535,      0,      0,\n         0,      0,      0,   2513,   7290,  14487,  24275,  35312,\n     46240,  55841,  62007,  65535,  65535,  65535,  65535,  65535,\n         0,      0,      0,      0,      0,      0,   3606,   9573,\n     18764,  28667,  40220,  51290,  59924,  65535,  65535,  65535,\n     65535,  65535,  65535,      0,      0,      0,      0,      0,\n         0,      0,   4879,  13091,  23376,  36061,  49395,  59315,\n     65535,  65535,  65535,  65535,  65535,  65535,  65535\n};\n\nconst SKP_uint16 SKP_Silk_shell_code_table_offsets[ 19 ] = {\n         0,      0,      3,      7,     12,     18,     25,     33,\n        42,     52,     63,     75,     88,    102,    117,    133,\n       150,    168,    187\n};\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_tables_sign.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_tables.h\"\n\nconst SKP_uint16 SKP_Silk_sign_CDF[ 36 ] = \n{\n         37840,  36944,  36251,  35304,\n         34715,  35503,  34529,  34296,\n         34016,  47659,  44945,  42503,\n         40235,  38569,  40254,  37851,\n         37243,  36595,  43410,  44121,\n         43127,  40978,  38845,  40433,\n         38252,  37795,  36637,  59159,\n         55630,  51806,  48073,  45036,\n         48416,  43857,  42678,  41146,\n};\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_tables_type_offset.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_tables.h\"\n\nconst SKP_uint16 SKP_Silk_type_offset_CDF[ 5 ] = {\n         0,  37522,  41030,  44212,  65535\n};\n\nconst SKP_int SKP_Silk_type_offset_CDF_offset = 2;\n\n\nconst SKP_uint16 SKP_Silk_type_offset_joint_CDF[ 4 ][ 5 ] = \n{\n{\n         0,  57686,  61230,  62358,  65535\n},\n{\n         0,  18346,  40067,  43659,  65535\n},\n{\n         0,  22694,  24279,  35507,  65535\n},\n{\n         0,   6067,   7215,  13010,  65535\n}\n};\n\n"
  },
  {
    "path": "app/jni/SKP_Silk_warped_autocorrelation_FIX.c",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main_FIX.h\"\n\n#define QC  10\n#define QS  14\n\n\n#if EMBEDDED_ARM<6\n/* Autocorrelations for a warped frequency axis */\nvoid SKP_Silk_warped_autocorrelation_FIX(\n          SKP_int32                 *corr,              /* O    Result [order + 1]                      */\n          SKP_int                   *scale,             /* O    Scaling of the correlation vector       */\n    const SKP_int16                 *input,             /* I    Input data to correlate                 */\n    const SKP_int16                 warping_Q16,        /* I    Warping coefficient                     */\n    const SKP_int                   length,             /* I    Length of input                         */\n    const SKP_int                   order               /* I    Correlation order (even)                */\n)\n{\n    SKP_int   n, i, lsh;\n    SKP_int32 tmp1_QS, tmp2_QS;\n    SKP_int32 state_QS[ MAX_SHAPE_LPC_ORDER + 1 ] = { 0 };\n    SKP_int64 corr_QC[  MAX_SHAPE_LPC_ORDER + 1 ] = { 0 };\n\n    /* Order must be even */\n    SKP_assert( ( order & 1 ) == 0 );\n    SKP_assert( 2 * QS - QC >= 0 );\n\n    /* Loop over samples */\n    for( n = 0; n < length; n++ ) {\n        tmp1_QS = SKP_LSHIFT32( ( SKP_int32 )input[ n ], QS );\n        /* Loop over allpass sections */\n        for( i = 0; i < order; i += 2 ) {\n            /* Output of allpass section */\n            tmp2_QS = SKP_SMLAWB( state_QS[ i ], state_QS[ i + 1 ] - tmp1_QS, warping_Q16 );\n            state_QS[ i ]  = tmp1_QS;\n            corr_QC[  i ] += SKP_RSHIFT64( SKP_SMULL( tmp1_QS, state_QS[ 0 ] ), 2 * QS - QC );\n            /* Output of allpass section */\n            tmp1_QS = SKP_SMLAWB( state_QS[ i + 1 ], state_QS[ i + 2 ] - tmp2_QS, warping_Q16 );\n            state_QS[ i + 1 ]  = tmp2_QS;\n            corr_QC[  i + 1 ] += SKP_RSHIFT64( SKP_SMULL( tmp2_QS, state_QS[ 0 ] ), 2 * QS - QC );\n        }\n        state_QS[ order ] = tmp1_QS;\n        corr_QC[  order ] += SKP_RSHIFT64( SKP_SMULL( tmp1_QS, state_QS[ 0 ] ), 2 * QS - QC );\n    }\n\n    lsh = SKP_Silk_CLZ64( corr_QC[ 0 ] ) - 35;\n    lsh = SKP_LIMIT( lsh, -12 - QC, 30 - QC );\n    *scale = -( QC + lsh ); \n    SKP_assert( *scale >= -30 && *scale <= 12 );\n    if( lsh >= 0 ) {\n        for( i = 0; i < order + 1; i++ ) {\n            corr[ i ] = ( SKP_int32 )SKP_CHECK_FIT32( SKP_LSHIFT64( corr_QC[ i ], lsh ) );\n        }\n    } else {\n        for( i = 0; i < order + 1; i++ ) {\n            corr[ i ] = ( SKP_int32 )SKP_CHECK_FIT32( SKP_RSHIFT64( corr_QC[ i ], -lsh ) );\n        }    \n    }\n    SKP_assert( corr_QC[ 0 ] >= 0 ); // If breaking, decrease QC\n}\n#endif\n\n"
  },
  {
    "path": "app/jni/decoder.c",
    "content": "#include \"silk.h\"\n#include \"lame.h\"\n#include <stdio.h>\n\nstatic void print_usage(char* argv[]) {\n    printf( \"\\nusage: %s in.bit out.pcm [settings]\\n\", argv[ 0 ] );\n    printf( \"\\nin.bit       : Bitstream input to decoder\" );\n    printf( \"\\nout.pcm      : Speech output from decoder\" );\n    printf( \"\\n   settings:\" );\n    printf( \"\\n-Fs_API <Hz> : Sampling rate of output signal in Hz; default: 24000\" );\n    printf( \"\\n-loss <perc> : Simulated packet loss percentage (0-100); default: 0\" );\n    printf( \"\\n-quiet       : Print out just some basic values\" );\n    printf( \"\\n\" );\n}\n\nint main( int argc, char* argv[] )\n{\n//    print_usage(argv);\n    const char *src = \"/home/ketian/silk_project/silk/msg_3910190915165fe46499e0f103.amr\";\n    const char *dest = \"/home/ketian/silk_project/silk/out2.pcm\";\n\n    FILE *tempFile = fopen(dest, \"wb+\");\n    if (tempFile == 0) {\n        LOGD(\"open tempFile %s failed\", tempFile);\n        return -1;\n    }\n    return convertSilk2PCM(src, tempFile);\n}\n"
  },
  {
    "path": "app/jni/decoder.cpp",
    "content": "//\n// Created by ketian on 16-9-23.\n//\n\n#include <jni.h>\n#include <unistd.h>\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n#include \"silk.h\"\n#include \"lame.h\"\n\nJNIEXPORT jint JNICALL\nJava_com_ketian_android_silkv3_jni_JNI_convert(JNIEnv *env, jobject thiz, jstring src, jstring dest, jstring tmpfile) {\n    if (src == nullptr){\n        return NULL;\n    }\n    if (dest == nullptr){\n        return NULL;\n    }\n    if (tmpfile == nullptr){\n        return NULL;\n    }\n    const char *str_c = env->GetStringUTFChars(src, nullptr);\n    const char *dest_c = env->GetStringUTFChars(dest, nullptr);\n    const char *tmp = env->GetStringUTFChars(tmpfile, nullptr);\n    LOGE(\"libsilkx is developed by tian.ke, any question, please email to ketn4391@gmail.com\");\n    LOGE(\"convert %s to %s\", str_c, dest_c);\n    FILE *tempFile = fopen(tmp, \"wb+e\");\n    if (tempFile == nullptr) {\n        LOGE(\"open tempFile %s failed\", tmp);\n        return -1;\n    }\n    if (convertSilk2PCM(str_c, tempFile) != 0) {\n        LOGE(\"convert silk to pcm failed\");\n        fclose(tempFile);\n        return -1;\n    }\n    lame_t lame = lame_init();\n    lame_set_in_samplerate(lame, 24000);\n\n    lame_set_num_channels(lame, 1);\n    lame_set_mode(lame, MONO);\n    lame_set_quality(lame, 5);\n    lame_init_params(lame);\n\n    FILE *pcm = tempFile;\n    fseek(pcm, 0, SEEK_SET);\n\n    FILE *mp3 = fopen(dest_c, \"wbe\");\n    int read, write;\n\n    const int PCM_SIZE = 8192;\n    const int MP3_SIZE = 8192;\n    short int pcm_buffer[PCM_SIZE];\n    unsigned char mp3_buffer[MP3_SIZE];\n\n    do {\n        read = static_cast<int>(fread(pcm_buffer, sizeof(short int), PCM_SIZE, pcm));\n        if (read == 0) {\n            write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);\n        } else {\n            write = lame_encode_buffer(lame, pcm_buffer, nullptr, read, mp3_buffer, MP3_SIZE);\n        }\n\n        fwrite(mp3_buffer, 1, static_cast<size_t>(write), mp3);\n    } while (read != 0);\n\n    lame_close(lame);\n    fclose(mp3);\n    fclose(pcm);\n\n    return 1;\n}\n\n#ifdef __cplusplus\n}\n#endif"
  },
  {
    "path": "app/jni/include/SKP_Silk_AsmHelper.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*\n * SKP_Silk_AsmHelper.h\n *\n *\n *\n *\n */\n \n \n#ifndef _SKP_ASM_HELPER_H_\n#define _SKP_ASM_HELPER_H_\n\n//  Register bank\n#define _REG 0\n#define _DREG 1\n\n//  Arg registers\n#define _R0 0\n#define _R1 1\n#define _R2 2\n#define _R3 3\n#define _R4 4\n//  GP registers\n#define _R5 5\n#define _R6 6\n#define _R7 7\n#define _R8 8\n#define _SB 9\n#define _SL 10\n// fp and ip registers\n#define _FP 11\n#define _IP 12\n// lr and sp registers\n#define _SP 13\n#define _LR 14\n\n\n// Extension register bank\n#define _numDReg \n\n#define _Q0 0\n#define _Q1 1\n#define _Q2 2\n#define _Q3 3\n#define _Q4 4\n#define _Q5 5\n#define _Q6 6\n#define _Q7 7\n#define _Q8 8\n#define _Q9 9\n#define _Q10 10\n#define _Q11 11\n#define _Q12 12\n#define _Q13 13\n#define _Q14 14\n#define _Q15 15\n\n#if defined (_WINRT)\n#else\n#if defined (IPHONE)\n#define MACRO\t\t\t.macro\n#define END_MACRO\t\t.endmacro\n#define ARG0_in\t\n#define ARG1_in\t\n#define ARG2_in\t\n#define ARG3_in\n#define ARG4_in\n#define ARG5_in\n#define ARG6_in\n#define ARG7_in\n#define ARG0\t\t\t$0\n#define ARG1\t\t\t$1\n#define ARG2\t\t\t$2\n#define ARG3\t\t\t$3\n#define ARG4\t\t\t$4\n#define ARG5\t\t\t$5\n#define ARG6\t\t\t$6\n#define ARG7\t\t\t$7\n#define RARG0\t\t\tr$0\n#define RARG1\t\t\tr$1\n#define QARG0\t\t\tq$0\n#define QARG1\t\t\tq$1\n\nMACRO CHECK_ABS\tARG0_in, ARG1_in\n\t.abs is_abs, ARG1\n\t.if\tis_abs==1\n\t\t.set ARG0, ARG1\n\t.else\n\t\t.set ARG0, -1\n\t.endif\nEND_MACRO\n\n#else\n#define MACRO\t\t\t.macro\n#define END_MACRO\t\t.endm\n#define ARG0_in\t\t\targ0=-1\n#define ARG1_in\t\t\targ1=-1\n#define ARG2_in\t\t\targ2=-1\n#define ARG3_in\t\t\targ3=-1\n#define ARG4_in\t\t\targ4=-1\n#define ARG5_in\t\t\targ5=-1\n#define ARG6_in\t\t\targ6=-1\n#define ARG7_in\t\t\targ7=-1\n#define ARG0\t\t\t\\arg0\n#define ARG1\t\t\t\\arg1\n#define ARG2\t\t\t\\arg2\n#define ARG3\t\t\t\\arg3\n#define ARG4\t\t\t\\arg4\n#define ARG5\t\t\t\\arg5\n#define ARG6\t\t\t\\arg6\n#define ARG7\t\t\t\\arg7\n#define RARG0\t\t\tr\\arg0\n#define RARG1\t\t\tr\\arg1\n#define QARG0\t\t\tq\\arg0\n#define QARG1\t\t\tq\\arg1\n\nMACRO CHECK_ABS\tARG0_in, ARG1_in\n\t.set ARG0, ARG1\nEND_MACRO\n#endif\n\nMACRO VARDEF ARG0_in, ARG1_in\nARG0\t.req\tARG1\nEND_MACRO\n\nMACRO VARDEFD ARG0_in, ARG1_in\nARG0\t.req\tARG1\nEND_MACRO\n\t\nMACRO VARDEFQ ARG0_in, ARG1_in\nARG0\t.req\tARG1\nEND_MACRO\n\nMACRO END\nEND_MACRO\n\nMACRO EXTERN ARG0_in\nEND_MACRO\n\nMACRO ALIGN ARG0_in\n.align ARG0\nEND_MACRO\n\nMACRO DATA\n.data\nEND_MACRO\n\nMACRO EXPORT ARG0_in\n.globl ARG0\nEND_MACRO\n\n#endif\n#endif\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_AsmPreproc.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/* SKP_Silk_AsmPreProc.h\n * \n * General header for all ARM asms uses SigProcLib. \n * It contains C preprocessor part and asm preprocessor part.\n * C preprocessor part: \n *\t\t* Interfacing makefile, arch, fpu and neon support\n *      * Interfacing different symbol styles and asm directives.\n *\t\t* Interfacing compiling time standard output\n * ASM preprocessor part:\n *\t\t* Defining general asm header/footer for stack/return value\n *\t\t* Allocating stack for local variables and nasted function\n *\t\t* Defining simple syntax checking and debugging routines\n */ \n\n\n/*\n * C preprocessor part\n */\n#ifndef _SKP_ASM_PREPROC_H_\n#define _SKP_ASM_PREPROC_H_\n\n#include \"SKP_Silk_AsmHelper.h\"\n\n\n/* Checking compilier __ARMEL__ defines */\n#if !__ARMEL__ && (!defined(NO_ASM)) && (!defined(_WINRT))\n#error\tCurrently SKP_Silk_AsmPreProc only supports little endian.\n// above line can be replaced by \n// #warning\t__ARMEL__=0\n// #define NOASM\n#endif\n\n/* Defining macro for different user label prefix. */                               \n#ifndef __USER_LABEL_PREFIX__\n#define __USER_LABEL_PREFIX__\n#endif\n\n#define CONCAT1(a, b) CONCAT2(a, b)\n#define CONCAT2(a, b) a ## b\n\n#define SYM(x) CONCAT1 (__USER_LABEL_PREFIX__, x)\n\n/* Remapping register for iphone. */\n\n#ifdef IPHONE\n#\tdefine _fp r7\n#\tdefine _r7 r11\n#else\n#\tdefine _fp fp\n#\tdefine _r7 r7\n#endif\n\n/* Checking compiler __ARM_EABI__ defines */\n\n#if __ARMEB__\n#define NO_ASM\t\t\t//remove asm optimization for ARM big endian.\n#else\n#define ARM_LITTLE_ENDIAN\n#endif\n\n/* Interfacing some asm directives to macros*/\n#define \tGBL\t\t.globl\n\n/* Legacy definition wrapper */\n#ifndef\tNO_ASM\n#if defined (__ARM_ARCH_4__) || defined (__ARM_ARCH_4T__) || defined (__ARM_ARCH_5__) || defined (__ARM_ARCH_5T__)\n#define EMBEDDED_ARM 4\n#define EMBEDDED_ARMv4\n#elif  defined (__ARM_ARCH_5TE__) || defined (__ARM_ARCH_5TEJ__)\n#define EMBEDDED_ARM 5\n#define EMBEDDED_ARMv5\n#elif defined (__ARM_ARCH_6__) ||defined (__ARM_ARCH_6J__) || defined (__ARM_ARCH_6Z__) || defined (__ARM_ARCH_6K__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__)\n#define EMBEDDED_ARM 6\n#define EMBEDDED_ARMv6\n#elif defined (__ARM_ARCH_7A__) && defined (__ARM_NEON__)\n#define EMBEDDED_ARM 7\n#define EMBEDDED_ARMv6\n#elif defined (__ARM_ARCH_7A__)\n#define EMBEDDED_ARM 6\n#define EMBEDDED_ARMv6\n#endif\n#endif\n\n#ifdef _WINRT\n#define L(a)\ta\n#define LR(a,d)\t%##d##a\n\n#define TABLE(L, symbol) symbol\n#else\n#define L(a) \ta:\n#define LR(a,d)\ta##d\n#define DCD\t.long\n#define DCW\t.short\n#define TABLE(L, symbol) L\n#endif\n\n#ifdef _WINRT\n#define streqh strheq\n#define strneh strhne\n#define strgth strhgt\n#define strlth strhlt\n#define ldrgtsh ldrshgt\n#define ldmgtia ldmiagt\n#define ldmgtdb ldmdbgt\n#define ldrneh ldrhne\n#define ldmltia ldmialt\n#endif\n/*\n *\tASM preprocessor part:\n */\n\n#ifdef _WINRT\n#else\n//\tAT&T Format\n#if EMBEDDED_ARM >= 7\n.set\t_ARCH, 7\n#elif EMBEDDED_ARM >= 6\n.set\t_ARCH, 6\n#elif EMBEDDED_ARM >= 5\t// Should be re-considerred as ARMv5 != ARMv5E\n.set\t_ARCH, 5\n#elif EMBEDDED_ARM >= 4\n.set\t_ARCH, 4\n#else\n.set\t_ARCH, 0\n#endif\n\n#if NEON\n.set\t_NEON, 1\n#else\n.set\t_NEON, 0\n#endif\n\nMACRO\tSKP_TABLE  ARG0_in, ARG1_in\nSYM(ARG0):\nEND_MACRO\n\n\n\nMACRO SKP_SMLAD\tARG0_in, ARG1_in, ARG2_in, ARG3_in\n#if EMBEDDED_ARM>=6\n\tsmlad\tARG0, ARG1, ARG2, ARG3\n#elif EMBEDDED_ARM>=5\n\tsmlabb\tARG0, ARG1, ARG2, ARG3\n\tsmlatt\tARG0, ARG1, ARG2, ARG0\n#else\n\t.abort \"SKP_SMUAD can't be used for armv4 or lower device..\"\n#endif\nEND_MACRO\n\nMACRO SKP_SMUAD\tARG0_in, ARG1_in, ARG2_in\n#if EMBEDDED_ARM>=6\n\tsmuad\tARG0, ARG1, ARG2\n#elif EMBEDDED_ARM>=5\n\tsmulbb\tARG0, ARG1, ARG2\n\tsmlatt\tARG0, ARG1, ARG2, ARG0\n#else\n\t.abort \"SKP_SMUAD can't be used for armv4 or lower device..\"\n#endif\nEND_MACRO\n\nMACRO SKP_SMLALD\tARG0_in, ARG1_in, ARG2_in, ARG3_in\n#if EMBEDDED_ARM>=6\n\tsmlald\tARG0, ARG1, ARG2, ARG3\n#elif EMBEDDED_ARM>=5\n\tsmlalbb\tARG0, ARG1, ARG2, ARG3\n\tsmlaltt\tARG0, ARG1, ARG2, ARG3\n#else\n\t.abort \"SKP_SMLALD can't be used for armv4 or lower device..\"\n#endif\nEND_MACRO\n\nMACRO SKP_RSHIFT_ROUND ARG0_in, ARG1_in, ARG2_in\n#if EMBEDDED_ARM>=4\n\tmov\t\tARG0, ARG1, asr #(ARG2-1)\n\tadd\t\tARG0, ARG0, #1\n\tmov\t\tARG0, ARG0, asr #1\n#else\n\t.abort \"SKP_RSHIFT_ROUND can't be used for armv3 or lower device..\"\n#endif\nEND_MACRO\n\nMACRO ADD_SHIFT ARG0_in, ARG1_in, ARG2_in, ARG3_in, ARG4_in\n\t\tadd ARG0, ARG1, ARG2, ARG3 ARG4\nEND_MACRO\n\nMACRO POST_IR \tARG0_in, ARG1_in, ARG2_in, ARG3_in\n\t\tARG0 ARG1, [ARG2], ARG3\nEND_MACRO\n\n#endif\n#endif //_SKP_ASM_PREPROC_H_\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_Inlines.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*! \\file SKP_Silk_Inlines.h\n *  \\brief SKP_Silk_Inlines.h defines inline signal processing functions.\n */\n\n#ifndef _SKP_SILK_FIX_INLINES_H_\n#define _SKP_SILK_FIX_INLINES_H_\n\n#include <assert.h>\n\n#ifdef  __cplusplus\nextern \"C\"\n{\n#endif\n\n/* count leading zeros of SKP_int64 */\nSKP_INLINE SKP_int32 SKP_Silk_CLZ64(SKP_int64 in)\n{\n    SKP_int32 in_upper;\n\n    in_upper = (SKP_int32)SKP_RSHIFT64(in, 32);\n    if (in_upper == 0) {\n        /* Search in the lower 32 bits */\n        return 32 + SKP_Silk_CLZ32( (SKP_int32) in );\n    } else {\n        /* Search in the upper 32 bits */\n        return SKP_Silk_CLZ32( in_upper );\n    }\n}\n\n/* get number of leading zeros and fractional part (the bits right after the leading one */\nSKP_INLINE void SKP_Silk_CLZ_FRAC(SKP_int32 in,            /* I: input */\n                                    SKP_int32 *lz,           /* O: number of leading zeros */\n                                    SKP_int32 *frac_Q7)      /* O: the 7 bits right after the leading one */\n{\n    SKP_int32 lzeros = SKP_Silk_CLZ32(in);\n\n    * lz = lzeros;\n    * frac_Q7 = SKP_ROR32(in, 24 - lzeros) & 0x7f;\n}\n\n/* Approximation of square root                                          */\n/* Accuracy: < +/- 10%  for output values > 15                           */\n/*           < +/- 2.5% for output values > 120                          */\nSKP_INLINE SKP_int32 SKP_Silk_SQRT_APPROX(SKP_int32 x)\n{\n    SKP_int32 y, lz, frac_Q7;\n\n    if( x <= 0 ) {\n        return 0;\n    }\n\n    SKP_Silk_CLZ_FRAC(x, &lz, &frac_Q7);\n\n    if( lz & 1 ) {\n        y = 32768;\n    } else {\n        y = 46214;        /* 46214 = sqrt(2) * 32768 */\n    }\n\n    /* get scaling right */\n    y >>= SKP_RSHIFT(lz, 1);\n\n    /* increment using fractional part of input */\n    y = SKP_SMLAWB(y, y, SKP_SMULBB(213, frac_Q7));\n\n    return y;\n}\n\n/* returns the number of left shifts before overflow for a 16 bit number (ITU definition with norm(0)=0) */\nSKP_INLINE SKP_int32 SKP_Silk_norm16(SKP_int16 a) {\n\n  SKP_int32 a32;\n\n  /* if ((a == 0) || (a == SKP_int16_MIN)) return(0); */\n  if ((a << 1) == 0) return(0);\n\n  a32 = a;\n  /* if (a32 < 0) a32 = -a32 - 1; */\n  a32 ^= SKP_RSHIFT(a32, 31);\n\n  return SKP_Silk_CLZ32(a32) - 17;\n}\n\n/* returns the number of left shifts before overflow for a 32 bit number (ITU definition with norm(0)=0) */\nSKP_INLINE SKP_int32 SKP_Silk_norm32(SKP_int32 a) {\n  \n  /* if ((a == 0) || (a == SKP_int32_MIN)) return(0); */\n  if ((a << 1) == 0) return(0);\n\n  /* if (a < 0) a = -a - 1; */\n  a ^= SKP_RSHIFT(a, 31);\n\n  return SKP_Silk_CLZ32(a) - 1;\n}\n\n/* Divide two int32 values and return result as int32 in a given Q-domain */\nSKP_INLINE SKP_int32 SKP_DIV32_varQ(    /* O    returns a good approximation of \"(a32 << Qres) / b32\" */\n    const SKP_int32     a32,            /* I    numerator (Q0)                  */\n    const SKP_int32     b32,            /* I    denominator (Q0)                */\n    const SKP_int       Qres            /* I    Q-domain of result (>= 0)       */\n)\n{\n    SKP_int   a_headrm, b_headrm, lshift;\n    SKP_int32 b32_inv, a32_nrm, b32_nrm, result;\n\n    SKP_assert( b32 != 0 );\n    SKP_assert( Qres >= 0 );\n\n    /* Compute number of bits head room and normalize inputs */\n    a_headrm = SKP_Silk_CLZ32( SKP_abs(a32) ) - 1;\n    a32_nrm = SKP_LSHIFT(a32, a_headrm);                                    /* Q: a_headrm                    */\n    b_headrm = SKP_Silk_CLZ32( SKP_abs(b32) ) - 1;\n    b32_nrm = SKP_LSHIFT(b32, b_headrm);                                    /* Q: b_headrm                    */\n\n    /* Inverse of b32, with 14 bits of precision */\n    b32_inv = SKP_DIV32_16( SKP_int32_MAX >> 2, SKP_RSHIFT(b32_nrm, 16) );  /* Q: 29 + 16 - b_headrm        */\n\n    /* First approximation */\n    result = SKP_SMULWB(a32_nrm, b32_inv);                                  /* Q: 29 + a_headrm - b_headrm    */\n\n    /* Compute residual by subtracting product of denominator and first approximation */\n    a32_nrm -= SKP_LSHIFT_ovflw( SKP_SMMUL(b32_nrm, result), 3 );           /* Q: a_headrm                    */\n\n    /* Refinement */\n    result = SKP_SMLAWB(result, a32_nrm, b32_inv);                          /* Q: 29 + a_headrm - b_headrm    */\n\n    /* Convert to Qres domain */\n    lshift = 29 + a_headrm - b_headrm - Qres;\n    if( lshift <= 0 ) {\n        return SKP_LSHIFT_SAT32(result, -lshift);\n    } else {\n        if( lshift < 32){\n            return SKP_RSHIFT(result, lshift);\n        } else {\n            /* Avoid undefined result */\n            return 0;\n        }\n    }\n}\n\n/* Invert int32 value and return result as int32 in a given Q-domain */\nSKP_INLINE SKP_int32 SKP_INVERSE32_varQ(    /* O    returns a good approximation of \"(1 << Qres) / b32\" */\n    const SKP_int32     b32,                /* I    denominator (Q0)                */\n    const SKP_int       Qres                /* I    Q-domain of result (> 0)        */\n)\n{\n    SKP_int   b_headrm, lshift;\n    SKP_int32 b32_inv, b32_nrm, err_Q32, result;\n\n    SKP_assert( b32 != 0 );\n    SKP_assert( b32 != SKP_int32_MIN ); /* SKP_int32_MIN is not handled by SKP_abs */\n    SKP_assert( Qres > 0 );\n\n    /* Compute number of bits head room and normalize input */\n    b_headrm = SKP_Silk_CLZ32( SKP_abs(b32) ) - 1;\n    b32_nrm = SKP_LSHIFT(b32, b_headrm);                                    /* Q: b_headrm                */\n\n    /* Inverse of b32, with 14 bits of precision */\n    b32_inv = SKP_DIV32_16( SKP_int32_MAX >> 2, SKP_RSHIFT(b32_nrm, 16) );  /* Q: 29 + 16 - b_headrm    */\n\n    /* First approximation */\n    result = SKP_LSHIFT(b32_inv, 16);                                       /* Q: 61 - b_headrm            */\n\n    /* Compute residual by subtracting product of denominator and first approximation from one */\n    err_Q32 = SKP_LSHIFT_ovflw( -SKP_SMULWB(b32_nrm, b32_inv), 3 );         /* Q32                        */\n\n    /* Refinement */\n    result = SKP_SMLAWW(result, err_Q32, b32_inv);                          /* Q: 61 - b_headrm            */\n\n    /* Convert to Qres domain */\n    lshift = 61 - b_headrm - Qres;\n    if( lshift <= 0 ) {\n        return SKP_LSHIFT_SAT32(result, -lshift);\n    } else {\n        if( lshift < 32){\n            return SKP_RSHIFT(result, lshift);\n        }else{\n            /* Avoid undefined result */\n            return 0;\n        }\n    }\n}\n\n#define SKP_SIN_APPROX_CONST0       (1073735400)\n#define SKP_SIN_APPROX_CONST1        (-82778932)\n#define SKP_SIN_APPROX_CONST2          (1059577)\n#define SKP_SIN_APPROX_CONST3            (-5013)\n\n/* Sine approximation; an input of 65536 corresponds to 2 * pi */\n/* Uses polynomial expansion of the input to the power 0, 2, 4 and 6 */\n/* The relative error is below 1e-5 */\nSKP_INLINE SKP_int32 SKP_Silk_SIN_APPROX_Q24(        /* O    returns approximately 2^24 * sin(x * 2 * pi / 65536) */\n    SKP_int32        x\n)\n{\n    SKP_int y_Q30;\n\n    /* Keep only bottom 16 bits (the function repeats itself with period 65536) */\n    x &= 65535;\n\n    /* Split range in four quadrants */\n    if( x <= 32768 ) {\n        if( x < 16384 ) {\n            /* Return cos(pi/2 - x) */\n            x = 16384 - x;\n        } else {\n            /* Return cos(x - pi/2) */\n            x -= 16384;\n        }\n        if( x < 1100 ) {\n            /* Special case: high accuracy */\n            return SKP_SMLAWB( 1 << 24, SKP_MUL( x, x ), -5053 );\n        }\n        x = SKP_SMULWB( SKP_LSHIFT( x, 8 ), x );        /* contains x^2 in Q20 */\n        y_Q30 = SKP_SMLAWB( SKP_SIN_APPROX_CONST2, x, SKP_SIN_APPROX_CONST3 );\n        y_Q30 = SKP_SMLAWW( SKP_SIN_APPROX_CONST1, x, y_Q30 );\n        y_Q30 = SKP_SMLAWW( SKP_SIN_APPROX_CONST0 + 66, x, y_Q30 );\n    } else {\n        if( x < 49152 ) {\n            /* Return -cos(3*pi/2 - x) */\n            x = 49152 - x;\n        } else {\n            /* Return -cos(x - 3*pi/2) */\n            x -= 49152;\n        }\n        if( x < 1100 ) {\n            /* Special case: high accuracy */\n            return SKP_SMLAWB( -1u << 24, SKP_MUL( x, x ), 5053 );\n        }\n        x = SKP_SMULWB( SKP_LSHIFT( x, 8 ), x );        /* contains x^2 in Q20 */\n        y_Q30 = SKP_SMLAWB( -SKP_SIN_APPROX_CONST2, x, -SKP_SIN_APPROX_CONST3 );\n        y_Q30 = SKP_SMLAWW( -SKP_SIN_APPROX_CONST1, x, y_Q30 );\n        y_Q30 = SKP_SMLAWW( -SKP_SIN_APPROX_CONST0, x, y_Q30 );\n    }\n    return SKP_RSHIFT_ROUND( y_Q30, 6 );\n}\n\n/* Cosine approximation; an input of 65536 corresponds to 2 * pi */\n/* The relative error is below 1e-5 */\nSKP_INLINE SKP_int32 SKP_Silk_COS_APPROX_Q24(        /* O    returns approximately 2^24 * cos(x * 2 * pi / 65536) */\n    SKP_int32        x\n)\n{\n    return SKP_Silk_SIN_APPROX_Q24( x + 16384 );\n}\n\n#ifdef  __cplusplus\n}\n#endif\n\n#endif /*_SKP_SILK_FIX_INLINES_H_*/\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_PLC.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_PLC_FIX_H\n#define SKP_SILK_PLC_FIX_H\n\n#include \"SKP_Silk_main.h\"\n\n#define BWE_COEF_Q16                    64880           /* 0.99 in Q16                      */\n#define V_PITCH_GAIN_START_MIN_Q14      11469           /* 0.7 in Q14                       */\n#define V_PITCH_GAIN_START_MAX_Q14      15565           /* 0.95 in Q14                      */\n#define MAX_PITCH_LAG_MS                18\n#define SA_THRES_Q8                     50\n#define USE_SINGLE_TAP                  1\n#define RAND_BUF_SIZE                   128\n#define RAND_BUF_MASK                   (RAND_BUF_SIZE - 1)\n#define LOG2_INV_LPC_GAIN_HIGH_THRES    3               /* 2^3 = 8 dB LPC gain              */\n#define LOG2_INV_LPC_GAIN_LOW_THRES     8               /* 2^8 = 24 dB LPC gain             */\n#define PITCH_DRIFT_FAC_Q16             655             /* 0.01 in Q16                      */\n\nvoid SKP_Silk_PLC_Reset(\n    SKP_Silk_decoder_state      *psDec              /* I/O Decoder state        */\n);\n\nvoid SKP_Silk_PLC(\n    SKP_Silk_decoder_state      *psDec,             /* I/O Decoder state        */\n    SKP_Silk_decoder_control    *psDecCtrl,         /* I/O Decoder control      */\n    SKP_int16                   signal[],           /* I/O  signal              */\n    SKP_int                     length,             /* I length of residual     */\n    SKP_int                     lost                /* I Loss flag              */\n);\n\nvoid SKP_Silk_PLC_update(\n    SKP_Silk_decoder_state      *psDec,             /* I/O Decoder state        */\n    SKP_Silk_decoder_control    *psDecCtrl,         /* I/O Decoder control      */\n    SKP_int16                   signal[],\n    SKP_int                     length\n);\n\nvoid SKP_Silk_PLC_conceal(\n    SKP_Silk_decoder_state      *psDec,             /* I/O Decoder state        */\n    SKP_Silk_decoder_control    *psDecCtrl,         /* I/O Decoder control      */\n    SKP_int16                   signal[],           /* O LPC residual signal    */\n    SKP_int                     length              /* I length of signal       */\n);\n\nvoid SKP_Silk_PLC_glue_frames(\n    SKP_Silk_decoder_state      *psDec,             /* I/O decoder state        */\n    SKP_Silk_decoder_control    *psDecCtrl,         /* I/O Decoder control      */\n    SKP_int16                   signal[],           /* I/O signal               */\n    SKP_int                     length              /* I length of signal       */\n);\n\n#endif\n\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_SDK_API.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_SDK_API_H\n#define SKP_SILK_SDK_API_H\n\n#include \"SKP_Silk_control.h\"\n#include \"SKP_Silk_typedef.h\"\n#include \"SKP_Silk_errors.h\"\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n#define SILK_MAX_FRAMES_PER_PACKET  5\n\n/* Struct for TOC (Table of Contents) */\ntypedef struct {\n    SKP_int     framesInPacket;                             /* Number of 20 ms frames in packet     */\n    SKP_int     fs_kHz;                                     /* Sampling frequency in packet         */\n    SKP_int     inbandLBRR;                                 /* Does packet contain LBRR information */\n    SKP_int     corrupt;                                    /* Packet is corrupt                    */\n    SKP_int     vadFlags[     SILK_MAX_FRAMES_PER_PACKET ]; /* VAD flag for each frame in packet    */\n    SKP_int     sigtypeFlags[ SILK_MAX_FRAMES_PER_PACKET ]; /* Signal type for each frame in packet */\n} SKP_Silk_TOC_struct;\n\n/****************************************/\n/* Encoder functions                    */\n/****************************************/\n\n/***********************************************/\n/* Get size in bytes of the Silk encoder state */\n/***********************************************/\nSKP_int SKP_Silk_SDK_Get_Encoder_Size( \n    SKP_int32                           *encSizeBytes   /* O:   Number of bytes in SILK encoder state           */\n);\n\n/*************************/\n/* Init or reset encoder */\n/*************************/\nSKP_int SKP_Silk_SDK_InitEncoder(\n    void                                *encState,      /* I/O: State                                           */\n    SKP_SILK_SDK_EncControlStruct       *encStatus      /* O:   Encoder Status                                  */\n);\n\n/***************************************/\n/* Read control structure from encoder */\n/***************************************/\nSKP_int SKP_Silk_SDK_QueryEncoder(\n    const void                          *encState,      /* I:   State                                           */\n    SKP_SILK_SDK_EncControlStruct       *encStatus      /* O:   Encoder Status                                  */\n);\n\n/**************************/\n/* Encode frame with Silk */\n/**************************/\nSKP_int SKP_Silk_SDK_Encode( \n    void                                *encState,      /* I/O: State                                           */\n    const SKP_SILK_SDK_EncControlStruct *encControl,    /* I:   Control status                                  */\n    const SKP_int16                     *samplesIn,     /* I:   Speech sample input vector                      */\n    SKP_int                             nSamplesIn,     /* I:   Number of samples in input vector               */\n    SKP_uint8                           *outData,       /* O:   Encoded output vector                           */\n    SKP_int16                           *nBytesOut      /* I/O: Number of bytes in outData (input: Max bytes)   */\n);\n\n/****************************************/\n/* Decoder functions                    */\n/****************************************/\n\n/***********************************************/\n/* Get size in bytes of the Silk decoder state */\n/***********************************************/\nSKP_int SKP_Silk_SDK_Get_Decoder_Size( \n    SKP_int32                           *decSizeBytes   /* O:   Number of bytes in SILK decoder state           */\n);\n\n/*************************/\n/* Init or Reset decoder */\n/*************************/\nSKP_int SKP_Silk_SDK_InitDecoder( \n    void                                *decState       /* I/O: State                                           */\n);\n\n/******************/\n/* Decode a frame */\n/******************/\nSKP_int SKP_Silk_SDK_Decode(\n    void*                               decState,       /* I/O: State                                           */\n    SKP_SILK_SDK_DecControlStruct*      decControl,     /* I/O: Control Structure                               */\n    SKP_int                             lostFlag,       /* I:   0: no loss, 1 loss                              */\n    const SKP_uint8                     *inData,        /* I:   Encoded input vector                            */\n    const SKP_int                       nBytesIn,       /* I:   Number of input bytes                           */\n    SKP_int16                           *samplesOut,    /* O:   Decoded output speech vector                    */\n    SKP_int16                           *nSamplesOut    /* I/O: Number of samples (vector/decoded)              */\n);\n\n/***************************************************************/\n/* Find Low Bit Rate Redundancy (LBRR) information in a packet */\n/***************************************************************/\nvoid SKP_Silk_SDK_search_for_LBRR(\n    const SKP_uint8                     *inData,        /* I:   Encoded input vector                            */\n    const SKP_int                       nBytesIn,       /* I:   Number of input Bytes                           */\n    SKP_int                             lost_offset,    /* I:   Offset from lost packet                         */\n    SKP_uint8                           *LBRRData,      /* O:   LBRR payload                                    */\n    SKP_int16                           *nLBRRBytes     /* O:   Number of LBRR Bytes                            */\n);\n\n/**************************************/\n/* Get table of contents for a packet */\n/**************************************/\nvoid SKP_Silk_SDK_get_TOC(\n    const SKP_uint8                     *inData,        /* I:   Encoded input vector                            */\n    const SKP_int                       nBytesIn,       /* I:   Number of input bytes                           */\n    SKP_Silk_TOC_struct                 *Silk_TOC       /* O:   Table of contents                               */\n);\n\n/**************************/\n/* Get the version number */\n/**************************/\n/* Return a pointer to string specifying the version */ \nconst char *SKP_Silk_SDK_get_version();\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_SigProc_FIX.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef _SKP_SILK_SIGPROC_FIX_H_\n#define _SKP_SILK_SIGPROC_FIX_H_\n\n#ifdef  __cplusplus\nextern \"C\"\n{\n#endif\n\n#define SKP_Silk_MAX_ORDER_LPC            16                    /* max order of the LPC analysis in schur() and k2a()    */\n#define SKP_Silk_MAX_CORRELATION_LENGTH   640                   /* max input length to the correlation                    */\n#include \"SKP_Silk_typedef.h\"\n#include <string.h>\n#include <stdlib.h>                                            /* for abs() */\n#include \"SKP_Silk_resampler_structs.h\"\n\n#include \"SKP_Silk_macros.h\"\n\n/********************************************************************/\n/*                    SIGNAL PROCESSING FUNCTIONS                   */\n/********************************************************************/\n\n/*!\n * Initialize/reset the resampler state for a given pair of input/output sampling rates \n*/\nSKP_int SKP_Silk_resampler_init( \n\tSKP_Silk_resampler_state_struct\t*S,\t\t    /* I/O: Resampler state \t\t\t*/\n\tSKP_int32\t\t\t\t\t\t\tFs_Hz_in,\t/* I:\tInput sampling rate (Hz)\t*/\n\tSKP_int32\t\t\t\t\t\t\tFs_Hz_out\t/* I:\tOutput sampling rate (Hz)\t*/\n);\n\n\n/*!\n * Clear the states of all resampling filters, without resetting sampling rate ratio \n */\nSKP_int SKP_Silk_resampler_clear( \n\tSKP_Silk_resampler_state_struct\t*S\t\t    /* I/O: Resampler state \t\t\t*/\n);\n\n/*!\n * Resampler: convert from one sampling rate to another\n */\nSKP_int SKP_Silk_resampler( \n\tSKP_Silk_resampler_state_struct\t*S,\t\t    /* I/O: Resampler state \t\t\t*/\n\tSKP_int16\t\t\t\t\t\t\tout[],\t    /* O:\tOutput signal \t\t\t\t*/\n\tconst SKP_int16\t\t\t\t\t\tin[],\t    /* I:\tInput signal\t\t\t\t*/\n\tSKP_int32\t\t\t\t\t\t\tinLen\t    /* I:\tNumber of input samples\t\t*/\n);\n\n/*!\n Upsample 2x, low quality \n */\nvoid SKP_Silk_resampler_up2(\n    SKP_int32                           *S,         /* I/O: State vector [ 2 ]                  */\n    SKP_int16                           *out,       /* O:   Output signal [ 2 * len ]           */\n    const SKP_int16                     *in,        /* I:   Input signal [ len ]                */\n    SKP_int32                           len         /* I:   Number of input samples             */\n);\n\n/*!\n* Downsample 2x, mediocre quality \n*/\nvoid SKP_Silk_resampler_down2(\n    SKP_int32                           *S,         /* I/O: State vector [ 2 ]                  */\n    SKP_int16                           *out,       /* O:   Output signal [ len ]               */\n    const SKP_int16                     *in,        /* I:   Input signal [ floor(len/2) ]       */\n    SKP_int32                           inLen       /* I:   Number of input samples             */\n);\n\n\n/*!\n * Downsample by a factor 2/3, low quality\n*/\nvoid SKP_Silk_resampler_down2_3(\n    SKP_int32                           *S,         /* I/O: State vector [ 6 ]                  */\n    SKP_int16                           *out,       /* O:   Output signal [ floor(2*inLen/3) ]  */\n    const SKP_int16                     *in,        /* I:   Input signal [ inLen ]              */\n    SKP_int32                           inLen       /* I:   Number of input samples             */\n);\n\n/*!\n * Downsample by a factor 3, low quality\n*/\nvoid SKP_Silk_resampler_down3(\n    SKP_int32                           *S,         /* I/O: State vector [ 8 ]                  */\n    SKP_int16                           *out,       /* O:   Output signal [ floor(inLen/3) ]    */\n    const SKP_int16                     *in,        /* I:   Input signal [ inLen ]              */\n    SKP_int32                           inLen       /* I:   Number of input samples             */\n);\n\n/*! \n * second order ARMA filter\n * can handle (slowly) varying coefficients \n */\nvoid SKP_Silk_biquad(\n    const SKP_int16      *in,          /* I:   input signal                */\n    const SKP_int16      *B,           /* I:   MA coefficients, Q13 [3]    */\n    const SKP_int16      *A,           /* I:   AR coefficients, Q13 [2]    */\n          SKP_int32      *S,           /* I/O: state vector [2]            */\n          SKP_int16      *out,         /* O:   output signal               */\n    const SKP_int32      len           /* I:   signal length               */\n);\n/*!\n * Second order ARMA filter; \n * slower than biquad() but uses more precise coefficients\n * can handle (slowly) varying coefficients \n */\nvoid SKP_Silk_biquad_alt(\n    const SKP_int16     *in,           /* I:    Input signal                 */\n    const SKP_int32     *B_Q28,        /* I:    MA coefficients [3]          */\n    const SKP_int32     *A_Q28,        /* I:    AR coefficients [2]          */\n    SKP_int32           *S,            /* I/O:  State vector [2]             */\n    SKP_int16           *out,          /* O:    Output signal                */\n    const SKP_int32     len            /* I:    Signal length (must be even) */\n);\n\n/*! \n * variable order MA filter. Prediction error filter implementation. Coeficients negated and starting with coef to x[n - 1]\n */\nvoid SKP_Silk_MA_Prediction(\n    const SKP_int16      *in,          /* I:   Input signal                                */\n    const SKP_int16      *B,           /* I:   MA prediction coefficients, Q12 [order]     */\n    SKP_int32            *S,           /* I/O: State vector [order]                        */\n    SKP_int16            *out,         /* O:   Output signal                               */\n    const SKP_int32      len,          /* I:   Signal length                               */\n    const SKP_int32      order         /* I:   Filter order                                */\n);\n\n/*!\n * 16th order AR filter for LPC synthesis, coefficients are in Q12\n */\nvoid SKP_Silk_LPC_synthesis_order16(\n    const SKP_int16      *in,          /* I:   excitation signal                            */\n    const SKP_int16      *A_Q12,       /* I:   AR coefficients [16], between -8_Q0 and 8_Q0 */\n    const SKP_int32      Gain_Q26,     /* I:   gain                                         */\n          SKP_int32      *S,           /* I/O: state vector [16]                            */\n          SKP_int16      *out,         /* O:   output signal                                */\n    const SKP_int32      len           /* I:   signal length, must be multiple of 16        */\n);\n\n/* variable order MA prediction error filter. */\n/* Inverse filter of SKP_Silk_LPC_synthesis_filter */\nvoid SKP_Silk_LPC_analysis_filter(\n    const SKP_int16      *in,          /* I:   Input signal                                */\n    const SKP_int16      *B,           /* I:   MA prediction coefficients, Q12 [order]     */\n    SKP_int16            *S,           /* I/O: State vector [order]                        */\n    SKP_int16            *out,         /* O:   Output signal                               */\n    const SKP_int32      len,          /* I:   Signal length                               */\n    const SKP_int32      Order         /* I:   Filter order                                */\n);\n\n/* even order AR filter */\nvoid SKP_Silk_LPC_synthesis_filter(\n    const SKP_int16      *in,          /* I:   excitation signal                               */\n    const SKP_int16      *A_Q12,       /* I:   AR coefficients [Order], between -8_Q0 and 8_Q0 */\n    const SKP_int32      Gain_Q26,     /* I:   gain                                            */\n    SKP_int32            *S,           /* I/O: state vector [Order]                            */\n    SKP_int16            *out,         /* O:   output signal                                   */\n    const SKP_int32      len,          /* I:   signal length                                   */\n    const SKP_int        Order         /* I:   filter order, must be even                      */\n);\n\n/* Chirp (bandwidth expand) LP AR filter */\nvoid SKP_Silk_bwexpander( \n    SKP_int16            *ar,          /* I/O  AR filter to be expanded (without leading 1)    */\n    const SKP_int        d,            /* I    Length of ar                                    */\n    SKP_int32            chirp_Q16     /* I    Chirp factor (typically in the range 0 to 1)    */\n);\n\n/* Chirp (bandwidth expand) LP AR filter */\nvoid SKP_Silk_bwexpander_32( \n    SKP_int32            *ar,          /* I/O  AR filter to be expanded (without leading 1)    */\n    const SKP_int        d,            /* I    Length of ar                                    */\n    SKP_int32            chirp_Q16     /* I    Chirp factor in Q16                             */\n);\n\n/* Compute inverse of LPC prediction gain, and                           */\n/* test if LPC coefficients are stable (all poles within unit circle)    */\nSKP_int SKP_Silk_LPC_inverse_pred_gain( /* O:  Returns 1 if unstable, otherwise 0          */\n    SKP_int32            *invGain_Q30,  /* O:  Inverse prediction gain, Q30 energy domain  */\n    const SKP_int16      *A_Q12,        /* I:  Prediction coefficients, Q12 [order]        */\n    const SKP_int        order          /* I:  Prediction order                            */\n);\n\nSKP_int SKP_Silk_LPC_inverse_pred_gain_Q24( /* O:   Returns 1 if unstable, otherwise 0      */\n    SKP_int32           *invGain_Q30,   /* O:   Inverse prediction gain, Q30 energy domain  */\n    const SKP_int32     *A_Q24,         /* I:   Prediction coefficients, Q24 [order]        */\n    const SKP_int       order           /* I:   Prediction order                            */\n);\n\n/* split signal in two decimated bands using first-order allpass filters */\nvoid SKP_Silk_ana_filt_bank_1(\n    const SKP_int16      *in,           /* I:   Input signal [N]        */\n    SKP_int32            *S,            /* I/O: State vector [2]        */\n    SKP_int16            *outL,         /* O:   Low band [N/2]          */\n    SKP_int16            *outH,         /* O:   High band [N/2]         */\n    SKP_int32            *scratch,      /* I:   Scratch memory [3*N/2]  */\n    const SKP_int32      N              /* I:   Number of input samples */\n);\n\n/********************************************************************/\n/*                        SCALAR FUNCTIONS                          */\n/********************************************************************/\n\n/* Approximation of 128 * log2() (very close inverse of approx 2^() below) */\n/* Convert input to a log scale    */\nSKP_int32 SKP_Silk_lin2log(const SKP_int32 inLin);        /* I: Input in linear scale        */\n\n/* Approximation of a sigmoid function */\nSKP_int SKP_Silk_sigm_Q15(SKP_int in_Q5);\n\n/* approximation of 2^() (exact inverse of approx log2() above) */\n/* convert input to a linear scale    */ \nSKP_int32 SKP_Silk_log2lin(const SKP_int32 inLog_Q7);    /* I: input on log scale */ \n\n/* Function that returns the maximum absolut value of the input vector */\nSKP_int16 SKP_Silk_int16_array_maxabs(  /* O   Maximum absolute value, max: 2^15-1   */\n    const SKP_int16     *vec,           /* I   Input vector  [len]                   */ \n    const SKP_int32     len             /* I   Length of input vector                */\n);\n\n/* Compute number of bits to right shift the sum of squares of a vector    */\n/* of int16s to make it fit in an int32                                    */\nvoid SKP_Silk_sum_sqr_shift(\n    SKP_int32           *energy,        /* O   Energy of x, after shifting to the right            */\n    SKP_int             *shift,         /* O   Number of bits right shift applied to energy        */\n    const SKP_int16     *x,             /* I   Input vector                                        */\n    SKP_int             len             /* I   Length of input vector                              */\n);\n\n/* Calculates the reflection coefficients from the correlation sequence    */\n/* Faster than schur64(), but much less accurate.                          */\n/* Uses SMLAWB(), requiring armv5E and higher.                             */ \nSKP_int32 SKP_Silk_schur(               /* O:    Returns residual energy                   */\n    SKP_int16            *rc_Q15,       /* O:    reflection coefficients [order] Q15       */\n    const SKP_int32      *c,            /* I:    correlations [order+1]                    */\n    const SKP_int32      order          /* I:    prediction order                          */\n);\n\n/* Calculates the reflection coefficients from the correlation sequence    */\n/* Slower than schur(), but more accurate.                                 */\n/* Uses SMULL(), available on armv4                                        */\nSKP_int32 SKP_Silk_schur64(             /* O:  returns residual energy                     */\n    SKP_int32           rc_Q16[],       /* O:  Reflection coefficients [order] Q16         */\n    const SKP_int32     c[],            /* I:  Correlations [order+1]                      */\n    SKP_int32           order           /* I:  Prediction order                            */\n);\n\n/* Step up function, converts reflection coefficients to prediction coefficients */\nvoid SKP_Silk_k2a(\n    SKP_int32           *A_Q24,         /* O:  Prediction coefficients [order] Q24         */\n    const SKP_int16     *rc_Q15,        /* I:  Reflection coefficients [order] Q15         */\n    const SKP_int32     order           /* I:  Prediction order                            */\n);\n\n/* Step up function, converts reflection coefficients to prediction coefficients */\nvoid SKP_Silk_k2a_Q16(\n    SKP_int32           *A_Q24,         /* O:  Prediction coefficients [order] Q24         */\n    const SKP_int32     *rc_Q16,        /* I:  Reflection coefficients [order] Q16         */\n    const SKP_int32     order           /* I:  Prediction order                            */\n);\n\n/* Apply sine window to signal vector.                                      */\n/* Window types:                                                            */\n/*    1 -> sine window from 0 to pi/2                                       */\n/*    2 -> sine window from pi/2 to pi                                      */\n/* Every other sample is linearly interpolated, for speed.                  */\nvoid SKP_Silk_apply_sine_window(\n    SKP_int16                        px_win[],            /* O    Pointer to windowed signal                  */\n    const SKP_int16                  px[],                /* I    Pointer to input signal                     */\n    const SKP_int                    win_type,            /* I    Selects a window type                       */\n    const SKP_int                    length               /* I    Window length, multiple of 4                */\n);\n\n/* Compute autocorrelation */\nvoid SKP_Silk_autocorr( \n    SKP_int32           *results,       /* O  Result (length correlationCount)            */\n    SKP_int             *scale,         /* O  Scaling of the correlation vector           */\n    const SKP_int16     *inputData,     /* I  Input data to correlate                     */\n    const SKP_int       inputDataSize,  /* I  Length of input                             */\n    const SKP_int       correlationCount /* I  Number of correlation taps to compute      */\n);\n\n/* Pitch estimator */\n#define SKP_Silk_PITCH_EST_MIN_COMPLEX        0\n#define SKP_Silk_PITCH_EST_MID_COMPLEX        1\n#define SKP_Silk_PITCH_EST_MAX_COMPLEX        2\n\nvoid SKP_Silk_decode_pitch(\n    SKP_int            lagIndex,        /* I                                              */\n    SKP_int            contourIndex,    /* O                                              */\n    SKP_int            pitch_lags[],    /* O 4 pitch values                               */\n    SKP_int            Fs_kHz           /* I sampling frequency (kHz)                     */\n);\n\nSKP_int SKP_Silk_pitch_analysis_core(    /* O    Voicing estimate: 0 voiced, 1 unvoiced                      */\n    const SKP_int16  *signal,            /* I    Signal of length PITCH_EST_FRAME_LENGTH_MS*Fs_kHz           */\n    SKP_int          *pitch_out,         /* O    4 pitch lag values                                          */\n    SKP_int          *lagIndex,          /* O    Lag Index                                                   */\n    SKP_int          *contourIndex,      /* O    Pitch contour Index                                         */\n    SKP_int          *LTPCorr_Q15,       /* I/O  Normalized correlation; input: value from previous frame    */\n    SKP_int          prevLag,            /* I    Last lag of previous frame; set to zero is unvoiced         */\n    const SKP_int32  search_thres1_Q16,  /* I    First stage threshold for lag candidates 0 - 1              */\n    const SKP_int    search_thres2_Q15,  /* I    Final threshold for lag candidates 0 - 1                    */\n    const SKP_int    Fs_kHz,             /* I    Sample frequency (kHz)                                      */\n    const SKP_int    complexity,         /* I    Complexity setting, 0-2, where 2 is highest                 */\n\tconst SKP_int\t forLJC\t\t\t     /* I\t 1 if this function is called from LJC code, 0 otherwise.    */\n);\n\n/* parameter defining the size and accuracy of the piecewise linear    */\n/* cosine approximatin table.                                        */\n\n#define LSF_COS_TAB_SZ_FIX      128\n/* rom table with cosine values */\nextern const SKP_int SKP_Silk_LSFCosTab_FIX_Q12[ LSF_COS_TAB_SZ_FIX + 1 ];\n\n/* Compute Normalized Line Spectral Frequencies (NLSFs) from whitening filter coefficients        */\n/* If not all roots are found, the a_Q16 coefficients are bandwidth expanded until convergence.    */\nvoid SKP_Silk_A2NLSF(\n    SKP_int            *NLSF,            /* O    Normalized Line Spectral Frequencies, Q15 (0 - (2^15-1)), [d] */\n    SKP_int32          *a_Q16,           /* I/O  Monic whitening filter coefficients in Q16 [d]                */\n    const SKP_int      d                 /* I    Filter order (must be even)                                   */\n);\n\n/* compute whitening filter coefficients from normalized line spectral frequencies */\nvoid SKP_Silk_NLSF2A(\n    SKP_int16          *a,               /* o    monic whitening filter coefficients in Q12,  [d]    */\n    const SKP_int      *NLSF,            /* i    normalized line spectral frequencies in Q15, [d]    */\n    const SKP_int      d                 /* i    filter order (should be even)                       */\n);\n\nvoid SKP_Silk_insertion_sort_increasing(\n    SKP_int32            *a,            /* I/O   Unsorted / Sorted vector                */\n    SKP_int              *index,        /* O:    Index vector for the sorted elements    */\n    const SKP_int        L,             /* I:    Vector length                           */\n    const SKP_int        K              /* I:    Number of correctly sorted positions    */\n);\n\nvoid SKP_Silk_insertion_sort_decreasing_int16(\n    SKP_int16            *a,            /* I/O:  Unsorted / Sorted vector                */\n    SKP_int              *index,        /* O:    Index vector for the sorted elements    */\n    const SKP_int        L,             /* I:    Vector length                           */\n    const SKP_int        K              /* I:    Number of correctly sorted positions    */\n);\n\nvoid SKP_Silk_insertion_sort_increasing_all_values(\n     SKP_int             *a,            /* I/O:  Unsorted / Sorted vector                */\n     const SKP_int       L              /* I:    Vector length                           */\n);\n\n/* NLSF stabilizer, for a single input data vector */\nvoid SKP_Silk_NLSF_stabilize(\n          SKP_int        *NLSF_Q15,      /* I/O:  Unstable/stabilized normalized LSF vector in Q15 [L]                    */\n    const SKP_int        *NDeltaMin_Q15, /* I:    Normalized delta min vector in Q15, NDeltaMin_Q15[L] must be >= 1 [L+1] */\n    const SKP_int        L               /* I:    Number of NLSF parameters in the input vector                           */\n);\n\n/* Laroia low complexity NLSF weights */\nvoid SKP_Silk_NLSF_VQ_weights_laroia(\n    SKP_int              *pNLSFW_Q6,     /* O:    Pointer to input vector weights            [D x 1]       */\n    const SKP_int        *pNLSF_Q15,     /* I:    Pointer to input vector                    [D x 1]       */\n    const SKP_int        D               /* I:    Input vector dimension (even)                            */\n);\n\n/* Compute reflection coefficients from input signal */\nvoid SKP_Silk_burg_modified(        \n    SKP_int32            *res_nrg,           /* O   residual energy                                                 */\n    SKP_int              *res_nrgQ,          /* O   residual energy Q value                                         */\n    SKP_int32            A_Q16[],            /* O   prediction coefficients (length order)                          */\n    const SKP_int16      x[],                /* I   input signal, length: nb_subfr * ( D + subfr_length )           */\n    const SKP_int        subfr_length,       /* I   input signal subframe length (including D preceeding samples)   */\n    const SKP_int        nb_subfr,           /* I   number of subframes stacked in x                                */\n    const SKP_int32      WhiteNoiseFrac_Q32, /* I   fraction added to zero-lag autocorrelation                      */\n    const SKP_int        D                   /* I   order                                                           */\n);\n\n/* Copy and multiply a vector by a constant */\nvoid SKP_Silk_scale_copy_vector16( \n    SKP_int16            *data_out, \n    const SKP_int16      *data_in, \n    SKP_int32            gain_Q16,           /* I:   gain in Q16   */\n    const SKP_int        dataSize            /* I:   length        */\n);\n\n/* Some for the LTP related function requires Q26 to work.*/\nvoid SKP_Silk_scale_vector32_Q26_lshift_18( \n    SKP_int32            *data1,             /* I/O: Q0/Q18        */\n    SKP_int32            gain_Q26,           /* I:   Q26           */\n    SKP_int              dataSize            /* I:   length        */\n);\n\n/********************************************************************/\n/*                        INLINE ARM MATH                             */\n/********************************************************************/\n\n/*    return sum(inVec1[i]*inVec2[i])    */\n/*    inVec1 and inVec2 should be increasing ordered, and starting address should be 4 byte aligned. (a factor of 4)*/\nSKP_int32 SKP_Silk_inner_prod_aligned(\n    const SKP_int16* const inVec1,           /* I   input vector 1    */ \n    const SKP_int16* const inVec2,           /* I   input vector 2    */\n    const SKP_int          len               /* I   vector lengths    */\n);\n\nSKP_int64 SKP_Silk_inner_prod16_aligned_64(\n    const SKP_int16        *inVec1,          /* I   input vector 1    */\n    const SKP_int16        *inVec2,          /* I   input vector 2    */\n    const SKP_int          len               /* I   vector lengths    */\n);\n/********************************************************************/\n/*                                MACROS                            */\n/********************************************************************/\n\n/* Rotate a32 right by 'rot' bits. Negative rot values result in rotating\n   left. Output is 32bit int.\n   Note: contemporary compilers recognize the C expressions below and\n   compile them into 'ror' instructions if available. No need for inline ASM! */\n#if defined(EMBEDDED_MIPS)\n/* For MIPS (and most likely for ARM! and >=i486) we don't have to handle\n   negative rot's as only 5 bits of rot are encoded into ROR instructions. */\nSKP_INLINE SKP_int32 SKP_ROR32(SKP_int32 a32, SKP_int rot)\n{\n    SKP_uint32 _x = (SKP_uint32) a32;\n    SKP_uint32 _r = (SKP_uint32) rot;\n    return (SKP_int32) ((_x << (32 - _r)) | (_x >> _r));\n}\n#else\n/* PPC must use this generic implementation. */\nSKP_INLINE SKP_int32 SKP_ROR32( SKP_int32 a32, SKP_int rot )\n{\n    SKP_uint32 x = (SKP_uint32) a32;\n    SKP_uint32 r = (SKP_uint32) rot;\n    SKP_uint32 m = (SKP_uint32) -rot;\n    if(rot <= 0)\n        return (SKP_int32) ((x << m) | (x >> (32 - m)));\n    else\n        return (SKP_int32) ((x << (32 - r)) | (x >> r));\n}\n#endif\n\n/* Allocate SKP_int16 alligned to 4-byte memory address */\n#if EMBEDDED_ARM\n#if defined(_WIN32) && defined(_M_ARM)\n#define SKP_DWORD_ALIGN __declspec(align(4))\n#else\n#define SKP_DWORD_ALIGN __attribute__((aligned(4)))\n#endif\n#else\n#define SKP_DWORD_ALIGN\n#endif\n\n/* Useful Macros that can be adjusted to other platforms */\n#define SKP_memcpy(a, b, c)                memcpy((a), (b), (c))    /* Dest, Src, ByteCount */\n#define SKP_memset(a, b, c)                memset((a), (b), (c))    /* Dest, value, ByteCount */\n#define SKP_memmove(a, b, c)               memmove((a), (b), (c))    /* Dest, Src, ByteCount */\n/* fixed point macros */\n\n// (a32 * b32) output have to be 32bit int\n#define SKP_MUL(a32, b32)                  ((a32) * (b32))\n\n// (a32 * b32) output have to be 32bit uint\n#define SKP_MUL_uint(a32, b32)             SKP_MUL(a32, b32)\n\n// a32 + (b32 * c32) output have to be 32bit int\n#define SKP_MLA(a32, b32, c32)             SKP_ADD32((a32),((b32) * (c32)))\n\n/* ((a32 >> 16)  * (b32 >> 16)) output have to be 32bit int */\n#define SKP_SMULTT(a32, b32)\t\t\t(((a32) >> 16) * ((b32) >> 16))\n\n/* a32 + ((a32 >> 16)  * (b32 >> 16)) output have to be 32bit int */\n#define SKP_SMLATT(a32, b32, c32)          SKP_ADD32((a32),((b32) >> 16) * ((c32) >> 16))\n\n#define SKP_SMLALBB(a64, b16, c16)         SKP_ADD64((a64),(SKP_int64)((SKP_int32)(b16) * (SKP_int32)(c16)))\n\n// (a32 * b32)\n#define SKP_SMULL(a32, b32)                ((SKP_int64)(a32) * /*(SKP_int64)*/(b32))\n\n/* Adds two signed 32-bit values in a way that can overflow, while not relying on undefined behaviour\n   (just standard two's complement implementation-specific behaviour) */\n#define SKP_ADD32_ovflw(a, b)               ((SKP_int32)((SKP_uint32)(a) + (SKP_uint32)(b)))\n/* Subtractss two signed 32-bit values in a way that can overflow, while not relying on undefined behaviour\n   (just standard two's complement implementation-specific behaviour) */\n#define SKP_SUB32_ovflw(a, b)               ((SKP_int32)((SKP_uint32)(a) - (SKP_uint32)(b)))\n\n/* Multiply-accumulate macros that allow overflow in the addition (ie, no asserts in debug mode) */\n#define SKP_MLA_ovflw(a32, b32, c32)        SKP_ADD32_ovflw((a32), (SKP_uint32)(b32) * (SKP_uint32)(c32))\n#ifndef SKP_SMLABB_ovflw\n #define SKP_SMLABB_ovflw(a32, b32, c32)    SKP_ADD32_ovflw((a32), SKP_SMULBB((b32),(c32)))\n#endif\n#define SKP_SMLATT_ovflw(a32, b32, c32) \tSKP_ADD32_ovflw((a32), SKP_SMULTT((b32),(c32)))\n#define SKP_SMLAWB_ovflw(a32, b32, c32)\t    SKP_ADD32_ovflw((a32), SKP_SMULWB((b32),(c32)))\n#define SKP_SMLAWT_ovflw(a32, b32, c32)\t    SKP_ADD32_ovflw((a32), SKP_SMULWT((b32),(c32)))\n#define SKP_DIV32_16(a32, b16)             ((SKP_int32)((a32) / (b16)))\n#define SKP_DIV32(a32, b32)                ((SKP_int32)((a32) / (b32)))\n\n#define SKP_ADD32(a, b)                    ((a) + (b))\n#define SKP_ADD64(a, b)                    ((a) + (b))\n\n#define SKP_SUB32(a, b)                    ((a) - (b))\n\n#define SKP_SAT16(a)                       ((a) > SKP_int16_MAX ? SKP_int16_MAX : \\\n                                           ((a) < SKP_int16_MIN ? SKP_int16_MIN : (a)))\n#define SKP_SAT32(a)                       ((a) > SKP_int32_MAX ? SKP_int32_MAX : \\\n                                           ((a) < SKP_int32_MIN ? SKP_int32_MIN : (a)))\n\n#define SKP_CHECK_FIT16(a)                 (a)\n#define SKP_CHECK_FIT32(a)                 (a)\n\n#define SKP_ADD_SAT16(a, b)                (SKP_int16)SKP_SAT16( SKP_ADD32( (SKP_int32)(a), (b) ) )\n\n/* Add with saturation for positive input values */ \n#define SKP_ADD_POS_SAT32(a, b)            ((((a)+(b)) & 0x80000000)           ? SKP_int32_MAX : ((a)+(b)))\n\n#define SKP_LSHIFT32(a, shift)             ((a)<<(shift))                // shift >= 0, shift < 32\n#define SKP_LSHIFT64(a, shift)             ((a)<<(shift))                // shift >= 0, shift < 64\n#define SKP_LSHIFT(a, shift)               SKP_LSHIFT32(a, shift)        // shift >= 0, shift < 32\n\n#define SKP_RSHIFT32(a, shift)             ((a)>>(shift))                // shift >= 0, shift < 32\n#define SKP_RSHIFT64(a, shift)             ((a)>>(shift))                // shift >= 0, shift < 64\n#define SKP_RSHIFT(a, shift)               SKP_RSHIFT32(a, shift)        // shift >= 0, shift < 32\n\n/* saturates before shifting */\n#define SKP_LSHIFT_SAT32(a, shift)         (SKP_LSHIFT32( SKP_LIMIT_32( (a), SKP_RSHIFT32( SKP_int32_MIN, (shift) ),    \\\n                                                                          SKP_RSHIFT32( SKP_int32_MAX, (shift) ) ), (shift) ))\n\n#define SKP_LSHIFT_ovflw(a, shift)        ((a)<<(shift))        // shift >= 0, allowed to overflow\n#define SKP_LSHIFT_uint(a, shift)         ((a)<<(shift))        // shift >= 0\n#define SKP_RSHIFT_uint(a, shift)         ((a)>>(shift))        // shift >= 0\n\n#define SKP_ADD_LSHIFT(a, b, shift)       ((a) + SKP_LSHIFT((b), (shift)))            // shift >= 0\n#define SKP_ADD_LSHIFT32(a, b, shift)     SKP_ADD32((a), SKP_LSHIFT32((b), (shift)))    // shift >= 0\n#define SKP_ADD_RSHIFT(a, b, shift)       ((a) + SKP_RSHIFT((b), (shift)))            // shift >= 0\n#define SKP_ADD_RSHIFT32(a, b, shift)     SKP_ADD32((a), SKP_RSHIFT32((b), (shift)))    // shift >= 0\n#define SKP_ADD_RSHIFT_uint(a, b, shift)  ((a) + SKP_RSHIFT_uint((b), (shift)))        // shift >= 0\n#define SKP_SUB_LSHIFT32(a, b, shift)     SKP_SUB32((a), SKP_LSHIFT32((b), (shift)))    // shift >= 0\n#define SKP_SUB_RSHIFT32(a, b, shift)     SKP_SUB32((a), SKP_RSHIFT32((b), (shift)))    // shift >= 0\n\n/* Requires that shift > 0 */\n#define SKP_RSHIFT_ROUND(a, shift)        ((shift) == 1 ? ((a) >> 1) + ((a) & 1) : (((a) >> ((shift) - 1)) + 1) >> 1)\n#define SKP_RSHIFT_ROUND64(a, shift)      ((shift) == 1 ? ((a) >> 1) + ((a) & 1) : (((a) >> ((shift) - 1)) + 1) >> 1)\n\n/* Number of rightshift required to fit the multiplication */\n#define SKP_NSHIFT_MUL_32_32(a, b)        ( -(31- (32-SKP_Silk_CLZ32(SKP_abs(a)) + (32-SKP_Silk_CLZ32(SKP_abs(b))))) )\n\n#define SKP_min(a, b)                     (((a) < (b)) ? (a) : (b)) \n#define SKP_max(a, b)                     (((a) > (b)) ? (a) : (b))\n\n/* Macro to convert floating-point constants to fixed-point */\n#define SKP_FIX_CONST( C, Q )           ((SKP_int32)((C) * ((SKP_int64)1 << (Q)) + 0.5))\n\n/* SKP_min() versions with typecast in the function call */\nSKP_INLINE SKP_int SKP_min_int(SKP_int a, SKP_int b)\n{\n    return (((a) < (b)) ? (a) : (b));\n}\n\nSKP_INLINE SKP_int32 SKP_min_32(SKP_int32 a, SKP_int32 b)\n{\n    return (((a) < (b)) ? (a) : (b));\n}\n\n/* SKP_min() versions with typecast in the function call */\nSKP_INLINE SKP_int SKP_max_int(SKP_int a, SKP_int b)\n{\n    return (((a) > (b)) ? (a) : (b));\n}\nSKP_INLINE SKP_int16 SKP_max_16(SKP_int16 a, SKP_int16 b)\n{\n    return (((a) > (b)) ? (a) : (b));\n}\nSKP_INLINE SKP_int32 SKP_max_32(SKP_int32 a, SKP_int32 b)\n{\n    return (((a) > (b)) ? (a) : (b));\n}\n\n#define SKP_LIMIT( a, limit1, limit2)    ((limit1) > (limit2) ? ((a) > (limit1) ? (limit1) : ((a) < (limit2) ? (limit2) : (a))) \\\n                                                             : ((a) > (limit2) ? (limit2) : ((a) < (limit1) ? (limit1) : (a))))\n\n#define SKP_LIMIT_int SKP_LIMIT\n#define SKP_LIMIT_32 SKP_LIMIT\n\n//#define SKP_non_neg(a)                 ((a) & ((-(a)) >> (8 * sizeof(a) - 1)))   /* doesn't seem faster than SKP_max(0, a);\n\n#define SKP_abs(a)                       (((a) >  0)  ? (a) : -(a))            // Be careful, SKP_abs returns wrong when input equals to SKP_intXX_MIN\n#define SKP_abs_int32(a)                 (((a) ^ ((a) >> 31)) - ((a) >> 31))\n\n/* PSEUDO-RANDOM GENERATOR                                                          */\n/* Make sure to store the result as the seed for the next call (also in between     */\n/* frames), otherwise result won't be random at all. When only using some of the    */\n/* bits, take the most significant bits by right-shifting. Do not just mask off     */\n/* the lowest bits.                                                                 */\n#define SKP_RAND(seed)                   (SKP_MLA_ovflw(907633515, (seed), 196314165))\n\n// Add some multiplication functions that can be easily mapped to ARM.\n\n//    SKP_SMMUL: Signed top word multiply. \n//        ARMv6        2 instruction cycles. \n//        ARMv3M+        3 instruction cycles. use SMULL and ignore LSB registers.(except xM) \n//#define SKP_SMMUL(a32, b32)            (SKP_int32)SKP_RSHIFT(SKP_SMLAL(SKP_SMULWB((a32), (b32)), (a32), SKP_RSHIFT_ROUND((b32), 16)), 16)\n// the following seems faster on x86\n//#define SKP_SMMUL(a32, b32)              (SKP_int32)SKP_RSHIFT64(SKP_SMULL((a32), (b32)), 32)\n\n#include \"SKP_Silk_Inlines.h\"\n\n#ifdef  __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_common_pitch_est_defines.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SIGPROC_COMMON_PITCH_EST_DEFINES_H\n#define SIGPROC_COMMON_PITCH_EST_DEFINES_H\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/************************************************************/\n/* Definitions For Fix pitch estimator                      */\n/************************************************************/\n\n#define PITCH_EST_MAX_FS_KHZ                24 /* Maximum sampling frequency used */\n\n#define PITCH_EST_FRAME_LENGTH_MS           40 /* 40 ms */\n\n#define PITCH_EST_MAX_FRAME_LENGTH          (PITCH_EST_FRAME_LENGTH_MS * PITCH_EST_MAX_FS_KHZ)\n#define PITCH_EST_MAX_FRAME_LENGTH_ST_1     (PITCH_EST_MAX_FRAME_LENGTH >> 2)\n#define PITCH_EST_MAX_FRAME_LENGTH_ST_2     (PITCH_EST_MAX_FRAME_LENGTH >> 1)\n#define PITCH_EST_MAX_SF_FRAME_LENGTH       (PITCH_EST_SUB_FRAME * PITCH_EST_MAX_FS_KHZ)\n\n#define PITCH_EST_MAX_LAG_MS                18            /* 18 ms -> 56 Hz */\n#define PITCH_EST_MIN_LAG_MS                2            /* 2 ms -> 500 Hz */\n#define PITCH_EST_MAX_LAG                   (PITCH_EST_MAX_LAG_MS * PITCH_EST_MAX_FS_KHZ)\n#define PITCH_EST_MIN_LAG                   (PITCH_EST_MIN_LAG_MS * PITCH_EST_MAX_FS_KHZ)\n\n#define PITCH_EST_NB_SUBFR                  4\n\n#define PITCH_EST_D_SRCH_LENGTH             24\n\n#define PITCH_EST_MAX_DECIMATE_STATE_LENGTH 7\n\n#define PITCH_EST_NB_STAGE3_LAGS            5\n\n#define PITCH_EST_NB_CBKS_STAGE2            3\n#define PITCH_EST_NB_CBKS_STAGE2_EXT        11\n\n#define PITCH_EST_CB_mn2                    1\n#define PITCH_EST_CB_mx2                    2\n\n#define PITCH_EST_NB_CBKS_STAGE3_MAX        34\n#define PITCH_EST_NB_CBKS_STAGE3_MID        24\n#define PITCH_EST_NB_CBKS_STAGE3_MIN        16\n\nextern const SKP_int16 SKP_Silk_CB_lags_stage2[PITCH_EST_NB_SUBFR][PITCH_EST_NB_CBKS_STAGE2_EXT];\nextern const SKP_int16 SKP_Silk_CB_lags_stage3[PITCH_EST_NB_SUBFR][PITCH_EST_NB_CBKS_STAGE3_MAX];\nextern const SKP_int16 SKP_Silk_Lag_range_stage3[ SKP_Silk_PITCH_EST_MAX_COMPLEX + 1 ] [ PITCH_EST_NB_SUBFR ][ 2 ];\nextern const SKP_int16 SKP_Silk_cbk_sizes_stage3[ SKP_Silk_PITCH_EST_MAX_COMPLEX + 1 ];\nextern const SKP_int16 SKP_Silk_cbk_offsets_stage3[ SKP_Silk_PITCH_EST_MAX_COMPLEX + 1 ];\n\n#endif\n\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_control.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_CONTROL_H\n#define SKP_SILK_CONTROL_H\n\n#include \"SKP_Silk_typedef.h\"\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n/***********************************************/\n/* Structure for controlling encoder operation */\n/***********************************************/\ntypedef struct {\n    /* I:   Input signal sampling rate in Hertz; 8000/12000/16000/24000                     */\n    SKP_int32 API_sampleRate;\n\n    /* I:   Maximum internal sampling rate in Hertz; 8000/12000/16000/24000                 */\n    SKP_int32 maxInternalSampleRate;\n\n    /* I:   Number of samples per packet; must be equivalent of 20, 40, 60, 80 or 100 ms    */\n    SKP_int packetSize;\n\n    /* I:   Bitrate during active speech in bits/second; internally limited                 */\n    SKP_int32 bitRate;                        \n\n    /* I:   Uplink packet loss in percent (0-100)                                           */\n    SKP_int packetLossPercentage;\n    \n    /* I:   Complexity mode; 0 is lowest; 1 is medium and 2 is highest complexity           */\n    SKP_int complexity;\n\n    /* I:   Flag to enable in-band Forward Error Correction (FEC); 0/1                      */\n    SKP_int useInBandFEC;\n\n    /* I:   Flag to enable discontinuous transmission (DTX); 0/1                            */\n    SKP_int useDTX;\n} SKP_SILK_SDK_EncControlStruct;\n\n/**************************************************************************/\n/* Structure for controlling decoder operation and reading decoder status */\n/**************************************************************************/\ntypedef struct {\n    /* I:   Output signal sampling rate in Hertz; 8000/12000/16000/24000                    */\n    SKP_int32 API_sampleRate;\n\n    /* O:   Number of samples per frame                                                     */\n    SKP_int frameSize;\n\n    /* O:   Frames per packet 1, 2, 3, 4, 5                                                 */\n    SKP_int framesPerPacket;\n\n    /* O:   Flag to indicate that the decoder has remaining payloads internally             */\n    SKP_int moreInternalDecoderFrames;\n\n    /* O:   Distance between main payload and redundant payload in packets                  */\n    SKP_int inBandFECOffset;\n} SKP_SILK_SDK_DecControlStruct;\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_define.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_DEFINE_H\n#define SKP_SILK_DEFINE_H\n\n#include \"SKP_Silk_errors.h\"\n#include \"SKP_Silk_typedef.h\"\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n\n#define MAX_FRAMES_PER_PACKET                   5\n\n\n\n/* Limits on bitrate */\n#define MIN_TARGET_RATE_BPS                     5000\n#define MAX_TARGET_RATE_BPS                     100000\n\n/* Transition bitrates between modes */\n#define SWB2WB_BITRATE_BPS                      25000\n#define WB2SWB_BITRATE_BPS                      30000\n#define WB2MB_BITRATE_BPS                       14000\n#define MB2WB_BITRATE_BPS                       18000\n#define MB2NB_BITRATE_BPS                       10000\n#define NB2MB_BITRATE_BPS                       14000\n\n/* Integration/hysteresis threshold for lowering internal sample frequency */\n/* 30000000 -> 6 sec if bitrate is 5000 bps below limit; 3 sec if bitrate is 10000 bps below limit */\n#define ACCUM_BITS_DIFF_THRESHOLD               30000000 \n#define TARGET_RATE_TAB_SZ                      8\n\n/* DTX settings                                 */\n#define NO_SPEECH_FRAMES_BEFORE_DTX             5       /* eq 100 ms */\n#define MAX_CONSECUTIVE_DTX                     20      /* eq 400 ms */\n\n#define USE_LBRR                                1\n\n/* Amount of concecutive no FEC packets before telling JB */\n#define NO_LBRR_THRES                           10\n\n/* Maximum delay between real packet and LBRR packet */\n#define MAX_LBRR_DELAY                          2\n#define LBRR_IDX_MASK                           1\n\n#define INBAND_FEC_MIN_RATE_BPS                 18000  /* Dont use inband FEC below this total target rate  */\n#define LBRR_LOSS_THRES                         1   /* Start adding LBRR at this loss rate                  */\n\n/* LBRR usage defines */\n#define SKP_SILK_NO_LBRR                        0   /* No LBRR information for this packet                  */\n#define SKP_SILK_ADD_LBRR_TO_PLUS1              1   /* Add LBRR for this packet to packet n + 1             */\n#define SKP_SILK_ADD_LBRR_TO_PLUS2              2   /* Add LBRR for this packet to packet n + 2             */\n\n/* Frame termination indicator defines */\n#define SKP_SILK_LAST_FRAME                     0   /* Last frames in packet                                */\n#define SKP_SILK_MORE_FRAMES                    1   /* More frames to follow this one                       */\n#define SKP_SILK_LBRR_VER1                      2   /* LBRR information from packet n - 1                   */\n#define SKP_SILK_LBRR_VER2                      3   /* LBRR information from packet n - 2                   */\n#define SKP_SILK_EXT_LAYER                      4   /* Extension layers added                               */\n\n/* Number of Second order Sections for SWB detection HP filter */\n#define NB_SOS                                  3\n#define HP_8_KHZ_THRES                          10          /* average energy per sample, above 8 kHz       */\n#define CONCEC_SWB_SMPLS_THRES                  480 * 15    /* 300 ms                                       */\n#define WB_DETECT_ACTIVE_SPEECH_MS_THRES        15000       /* ms of active speech needed for WB detection  */\n\n/* Low complexity setting */\n#define LOW_COMPLEXITY_ONLY                     0\n\n/* Activate bandwidth transition filtering for mode switching */\n#define SWITCH_TRANSITION_FILTERING             1\n\n/* Decoder Parameters */\n#define DEC_HP_ORDER                            2\n\n/* Maximum sampling frequency, should be 16 for some embedded platforms */\n#define MAX_FS_KHZ                              24 \n#define MAX_API_FS_KHZ                          48\n\n/* Signal Types used by silk */\n#define SIG_TYPE_VOICED                         0\n#define SIG_TYPE_UNVOICED                       1\n\n/* VAD Types used by silk */\n#define NO_VOICE_ACTIVITY                       0\n#define VOICE_ACTIVITY                          1\n\n/* Number of samples per frame */ \n#define FRAME_LENGTH_MS                         20\n#define MAX_FRAME_LENGTH                        ( FRAME_LENGTH_MS * MAX_FS_KHZ )\n\n/* Milliseconds of lookahead for pitch analysis */\n#define LA_PITCH_MS                             2\n#define LA_PITCH_MAX                            ( LA_PITCH_MS * MAX_FS_KHZ )\n\n/* Length of LPC window used in find pitch */\n#define FIND_PITCH_LPC_WIN_MS                   ( 20 + (LA_PITCH_MS << 1) )\n#define FIND_PITCH_LPC_WIN_MAX                  ( FIND_PITCH_LPC_WIN_MS * MAX_FS_KHZ )\n\n/* Order of LPC used in find pitch */\n#define MAX_FIND_PITCH_LPC_ORDER                16\n\n#define PITCH_EST_COMPLEXITY_HC_MODE            SKP_Silk_PITCH_EST_MAX_COMPLEX\n#define PITCH_EST_COMPLEXITY_MC_MODE            SKP_Silk_PITCH_EST_MID_COMPLEX\n#define PITCH_EST_COMPLEXITY_LC_MODE            SKP_Silk_PITCH_EST_MIN_COMPLEX\n\n/* Milliseconds of lookahead for noise shape analysis */\n#define LA_SHAPE_MS                             5\n#define LA_SHAPE_MAX                            ( LA_SHAPE_MS * MAX_FS_KHZ )\n\n/* Max length of LPC window used in noise shape analysis */\n#define SHAPE_LPC_WIN_MAX                       ( 15 * MAX_FS_KHZ )\n\n/* Max number of bytes in payload output buffer (may contain multiple frames) */\n#define MAX_ARITHM_BYTES                        1024\n\n#define RANGE_CODER_WRITE_BEYOND_BUFFER         -1\n#define RANGE_CODER_CDF_OUT_OF_RANGE            -2\n#define RANGE_CODER_NORMALIZATION_FAILED        -3\n#define RANGE_CODER_ZERO_INTERVAL_WIDTH         -4\n#define RANGE_CODER_DECODER_CHECK_FAILED        -5\n#define RANGE_CODER_READ_BEYOND_BUFFER          -6\n#define RANGE_CODER_ILLEGAL_SAMPLING_RATE       -7\n#define RANGE_CODER_DEC_PAYLOAD_TOO_LONG        -8\n\n/* dB level of lowest gain quantization level */\n#define MIN_QGAIN_DB                            6\n/* dB level of highest gain quantization level */\n#define MAX_QGAIN_DB                            86\n/* Number of gain quantization levels */\n#define N_LEVELS_QGAIN                          64\n/* Max increase in gain quantization index */\n#define MAX_DELTA_GAIN_QUANT                    40\n/* Max decrease in gain quantization index */\n#define MIN_DELTA_GAIN_QUANT                    -4\n\n/* Quantization offsets (multiples of 4) */\n#define OFFSET_VL_Q10                           32\n#define OFFSET_VH_Q10                           100\n#define OFFSET_UVL_Q10                          100\n#define OFFSET_UVH_Q10                          256\n\n/* Maximum numbers of iterations used to stabilize a LPC vector */\n#define MAX_LPC_STABILIZE_ITERATIONS            20\n\n#define MAX_LPC_ORDER                           16\n#define MIN_LPC_ORDER                           10\n\n/* Find Pred Coef defines */\n#define LTP_ORDER                               5\n\n/* LTP quantization settings */\n#define NB_LTP_CBKS                             3\n\n/* Number of subframes */\n#define NB_SUBFR                                4\n\n/* Flag to use harmonic noise shaping */\n#define USE_HARM_SHAPING                        1\n\n/* Max LPC order of noise shaping filters */\n#define MAX_SHAPE_LPC_ORDER                     16\n\n#define HARM_SHAPE_FIR_TAPS                     3\n\n/* Maximum number of delayed decision states */\n#define MAX_DEL_DEC_STATES                      4\n\n#define LTP_BUF_LENGTH                          512\n#define LTP_MASK                                (LTP_BUF_LENGTH - 1)\n\n#define DECISION_DELAY                          32\n#define DECISION_DELAY_MASK                     (DECISION_DELAY - 1)\n\n/* number of subframes for excitation entropy coding */\n#define SHELL_CODEC_FRAME_LENGTH                16\n#define MAX_NB_SHELL_BLOCKS                     (MAX_FRAME_LENGTH / SHELL_CODEC_FRAME_LENGTH)\n\n/* number of rate levels, for entropy coding of excitation */\n#define N_RATE_LEVELS                           10\n\n/* maximum sum of pulses per shell coding frame */\n#define MAX_PULSES                              18\n\n#define MAX_MATRIX_SIZE                         MAX_LPC_ORDER /* Max of LPC Order and LTP order */\n\n#if( MAX_LPC_ORDER > DECISION_DELAY )\n# define NSQ_LPC_BUF_LENGTH                     MAX_LPC_ORDER\n#else\n# define NSQ_LPC_BUF_LENGTH                     DECISION_DELAY\n#endif\n\n/***********************/\n/* High pass filtering */\n/***********************/\n#define HIGH_PASS_INPUT                         1\n\n/***************************/\n/* Voice activity detector */\n/***************************/\n#define VAD_N_BANDS                             4\n\n#define VAD_INTERNAL_SUBFRAMES_LOG2             2\n#define VAD_INTERNAL_SUBFRAMES                  (1 << VAD_INTERNAL_SUBFRAMES_LOG2)\n    \n#define VAD_NOISE_LEVEL_SMOOTH_COEF_Q16         1024    /* Must be < 4096                                   */\n#define VAD_NOISE_LEVELS_BIAS                   50 \n\n/* Sigmoid settings */\n#define VAD_NEGATIVE_OFFSET_Q5                  128     /* sigmoid is 0 at -128                             */\n#define VAD_SNR_FACTOR_Q16                      45000 \n\n/* smoothing for SNR measurement */\n#define VAD_SNR_SMOOTH_COEF_Q18                 4096\n\n/******************/\n/* NLSF quantizer */\n/******************/\n#   define NLSF_MSVQ_MAX_CB_STAGES                      10  /* Update manually when changing codebooks      */\n#   define NLSF_MSVQ_MAX_VECTORS_IN_STAGE               128 /* Update manually when changing codebooks      */\n#   define NLSF_MSVQ_MAX_VECTORS_IN_STAGE_TWO_TO_END    16  /* Update manually when changing codebooks      */\n\n#define NLSF_MSVQ_FLUCTUATION_REDUCTION         1\n#define MAX_NLSF_MSVQ_SURVIVORS                 16\n#define MAX_NLSF_MSVQ_SURVIVORS_LC_MODE         2\n#define MAX_NLSF_MSVQ_SURVIVORS_MC_MODE         4\n\n/* Based on above defines, calculate how much memory is necessary to allocate */\n#if( NLSF_MSVQ_MAX_VECTORS_IN_STAGE > ( MAX_NLSF_MSVQ_SURVIVORS_LC_MODE * NLSF_MSVQ_MAX_VECTORS_IN_STAGE_TWO_TO_END ) )\n#   define NLSF_MSVQ_TREE_SEARCH_MAX_VECTORS_EVALUATED_LC_MODE  NLSF_MSVQ_MAX_VECTORS_IN_STAGE\n#else\n#   define NLSF_MSVQ_TREE_SEARCH_MAX_VECTORS_EVALUATED_LC_MODE  MAX_NLSF_MSVQ_SURVIVORS_LC_MODE * NLSF_MSVQ_MAX_VECTORS_IN_STAGE_TWO_TO_END\n#endif\n\n#if( NLSF_MSVQ_MAX_VECTORS_IN_STAGE > ( MAX_NLSF_MSVQ_SURVIVORS * NLSF_MSVQ_MAX_VECTORS_IN_STAGE_TWO_TO_END ) )\n#   define NLSF_MSVQ_TREE_SEARCH_MAX_VECTORS_EVALUATED  NLSF_MSVQ_MAX_VECTORS_IN_STAGE\n#else\n#   define NLSF_MSVQ_TREE_SEARCH_MAX_VECTORS_EVALUATED  MAX_NLSF_MSVQ_SURVIVORS * NLSF_MSVQ_MAX_VECTORS_IN_STAGE_TWO_TO_END\n#endif\n\n#define NLSF_MSVQ_SURV_MAX_REL_RD               0.1f    /* Must be < 0.5                                    */\n\n/* Transition filtering for mode switching */\n#if SWITCH_TRANSITION_FILTERING\n#  define TRANSITION_TIME_UP_MS                 5120 // 5120 = 64 * FRAME_LENGTH_MS * ( TRANSITION_INT_NUM - 1 ) = 64*(20*4)\n#  define TRANSITION_TIME_DOWN_MS               2560 // 2560 = 32 * FRAME_LENGTH_MS * ( TRANSITION_INT_NUM - 1 ) = 32*(20*4)\n#  define TRANSITION_NB                         3 /* Hardcoded in tables */\n#  define TRANSITION_NA                         2 /* Hardcoded in tables */\n#  define TRANSITION_INT_NUM                    5 /* Hardcoded in tables */\n#  define TRANSITION_FRAMES_UP                  ( TRANSITION_TIME_UP_MS   / FRAME_LENGTH_MS )\n#  define TRANSITION_FRAMES_DOWN                ( TRANSITION_TIME_DOWN_MS / FRAME_LENGTH_MS )\n#  define TRANSITION_INT_STEPS_UP               ( TRANSITION_FRAMES_UP    / ( TRANSITION_INT_NUM - 1 )  )\n#  define TRANSITION_INT_STEPS_DOWN             ( TRANSITION_FRAMES_DOWN  / ( TRANSITION_INT_NUM - 1 )  )\n#endif\n\n/* Row based */\n#define matrix_ptr(Matrix_base_adr, row, column, N)         *(Matrix_base_adr + ((row)*(N)+(column)))\n#define matrix_adr(Matrix_base_adr, row, column, N)          (Matrix_base_adr + ((row)*(N)+(column)))\n\n/* Column based */\n#ifndef matrix_c_ptr\n#   define matrix_c_ptr(Matrix_base_adr, row, column, M)    *(Matrix_base_adr + ((row)+(M)*(column)))\n#endif\n#define matrix_c_adr(Matrix_base_adr, row, column, M)        (Matrix_base_adr + ((row)+(M)*(column)))\n\n/* BWE factors to apply after packet loss */\n#define BWE_AFTER_LOSS_Q16                      63570\n\n/* Defines for CN generation */\n#define CNG_BUF_MASK_MAX                        255             /* 2^floor(log2(MAX_FRAME_LENGTH))-1    */\n#define CNG_GAIN_SMTH_Q16                       4634            /* 0.25^(1/4)                           */\n#define CNG_NLSF_SMTH_Q16                       16348           /* 0.25                                 */\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_errors.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_ERRORS_H\n#define SKP_SILK_ERRORS_H\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n/******************/\n/* Error messages */\n/******************/\n#define SKP_SILK_NO_ERROR                               0\n\n/**************************/\n/* Encoder error messages */\n/**************************/\n\n/* Input length is not a multiplum of 10 ms, or length is longer than the packet length */\n#define SKP_SILK_ENC_INPUT_INVALID_NO_OF_SAMPLES        -1\n\n/* Sampling frequency not 8000, 12000, 16000 or 24000 Hertz */\n#define SKP_SILK_ENC_FS_NOT_SUPPORTED                   -2\n\n/* Packet size not 20, 40, 60, 80 or 100 ms */\n#define SKP_SILK_ENC_PACKET_SIZE_NOT_SUPPORTED          -3\n\n/* Allocated payload buffer too short */\n#define SKP_SILK_ENC_PAYLOAD_BUF_TOO_SHORT              -4\n\n/* Loss rate not between 0 and 100 percent */\n#define SKP_SILK_ENC_INVALID_LOSS_RATE                  -5\n\n/* Complexity setting not valid, use 0, 1 or 2 */\n#define SKP_SILK_ENC_INVALID_COMPLEXITY_SETTING         -6\n\n/* Inband FEC setting not valid, use 0 or 1 */\n#define SKP_SILK_ENC_INVALID_INBAND_FEC_SETTING         -7\n\n/* DTX setting not valid, use 0 or 1 */\n#define SKP_SILK_ENC_INVALID_DTX_SETTING                -8\n\n/* Internal encoder error */\n#define SKP_SILK_ENC_INTERNAL_ERROR                     -9\n\n/**************************/\n/* Decoder error messages */\n/**************************/\n\n/* Output sampling frequency lower than internal decoded sampling frequency */\n#define SKP_SILK_DEC_INVALID_SAMPLING_FREQUENCY         -10\n\n/* Payload size exceeded the maximum allowed 1024 bytes */\n#define SKP_SILK_DEC_PAYLOAD_TOO_LARGE                  -11\n\n/* Payload has bit errors */\n#define SKP_SILK_DEC_PAYLOAD_ERROR                      -12\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_macros.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef _SKP_SILK_API_C_H_\n#define _SKP_SILK_API_C_H_\n\n// This is an inline header file for general platform.\n\n// (a32 * (SKP_int32)((SKP_int16)(b32))) >> 16 output have to be 32bit int\n#define SKP_SMULWB(a32, b32)            ((((a32) >> 16) * (SKP_int32)((SKP_int16)(b32))) + ((((a32) & 0x0000FFFF) * (SKP_int32)((SKP_int16)(b32))) >> 16))\n\n// a32 + (b32 * (SKP_int32)((SKP_int16)(c32))) >> 16 output have to be 32bit int\n#define SKP_SMLAWB(a32, b32, c32)       ((a32) + ((((b32) >> 16) * (SKP_int32)((SKP_int16)(c32))) + ((((b32) & 0x0000FFFF) * (SKP_int32)((SKP_int16)(c32))) >> 16)))\n\n// (a32 * (b32 >> 16)) >> 16\n#define SKP_SMULWT(a32, b32)            (((a32) >> 16) * ((b32) >> 16) + ((((a32) & 0x0000FFFF) * ((b32) >> 16)) >> 16))\n\n// a32 + (b32 * (c32 >> 16)) >> 16\n#define SKP_SMLAWT(a32, b32, c32)       ((a32) + (((b32) >> 16) * ((c32) >> 16)) + ((((b32) & 0x0000FFFF) * ((c32) >> 16)) >> 16))\n\n// (SKP_int32)((SKP_int16)(a3))) * (SKP_int32)((SKP_int16)(b32)) output have to be 32bit int\n#define SKP_SMULBB(a32, b32)            ((SKP_int32)((SKP_int16)(a32)) * (SKP_int32)((SKP_int16)(b32)))\n\n// a32 + (SKP_int32)((SKP_int16)(b32)) * (SKP_int32)((SKP_int16)(c32)) output have to be 32bit int\n#define SKP_SMLABB(a32, b32, c32)       ((a32) + ((SKP_int32)((SKP_int16)(b32))) * (SKP_int32)((SKP_int16)(c32)))\n\n// (SKP_int32)((SKP_int16)(a32)) * (b32 >> 16)\n#define SKP_SMULBT(a32, b32)            ((SKP_int32)((SKP_int16)(a32)) * ((b32) >> 16))\n\n// a32 + (SKP_int32)((SKP_int16)(b32)) * (c32 >> 16)\n#define SKP_SMLABT(a32, b32, c32)       ((a32) + ((SKP_int32)((SKP_int16)(b32))) * ((c32) >> 16))\n\n// a64 + (b32 * c32)\n#define SKP_SMLAL(a64, b32, c32)        (SKP_ADD64((a64), ((SKP_int64)(b32) * (SKP_int64)(c32))))\n\n// (a32 * b32) >> 16\n#define SKP_SMULWW(a32, b32)            SKP_MLA(SKP_SMULWB((a32), (b32)), (a32), SKP_RSHIFT_ROUND((b32), 16))\n\n// a32 + ((b32 * c32) >> 16)\n#define SKP_SMLAWW(a32, b32, c32)       SKP_MLA(SKP_SMLAWB((a32), (b32), (c32)), (b32), SKP_RSHIFT_ROUND((c32), 16))\n\n// (SKP_int32)(((SKP_int64)a32 * b32) >> 32)\n#define SKP_SMMUL(a32, b32)             (SKP_int32)SKP_RSHIFT64(SKP_SMULL((a32), (b32)), 32)\n\n/* add/subtract with output saturated */\n#define SKP_ADD_SAT32(a, b)             ((((a) + (b)) & 0x80000000) == 0 ?                              \\\n                                        ((((a) & (b)) & 0x80000000) != 0 ? SKP_int32_MIN : (a)+(b)) :   \\\n                                        ((((a) | (b)) & 0x80000000) == 0 ? SKP_int32_MAX : (a)+(b)) )\n\n#define SKP_SUB_SAT32(a, b)             ((((a)-(b)) & 0x80000000) == 0 ?                                        \\\n                                        (( (a) & ((b)^0x80000000) & 0x80000000) ? SKP_int32_MIN : (a)-(b)) :    \\\n                                        ((((a)^0x80000000) & (b)  & 0x80000000) ? SKP_int32_MAX : (a)-(b)) )\n    \nSKP_INLINE SKP_int32 SKP_Silk_CLZ16(SKP_int16 in16)\n{\n    SKP_int32 out32 = 0;\n    if( in16 == 0 ) {\n        return 16;\n    }\n    /* test nibbles */\n    if( in16 & 0xFF00 ) {\n        if( in16 & 0xF000 ) {\n            in16 >>= 12;\n        } else {\n            out32 += 4;\n            in16 >>= 8;\n        }\n    } else {\n        if( in16 & 0xFFF0 ) {\n            out32 += 8;\n            in16 >>= 4;\n        } else {\n            out32 += 12;\n        }\n    }\n    /* test bits and return */\n    if( in16 & 0xC ) {\n        if( in16 & 0x8 )\n            return out32 + 0;\n        else\n            return out32 + 1;\n    } else {\n        if( in16 & 0xE )\n            return out32 + 2;\n        else\n            return out32 + 3;\n    }\n}\n\nSKP_INLINE SKP_int32 SKP_Silk_CLZ32(SKP_int32 in32)\n{\n    /* test highest 16 bits and convert to SKP_int16 */\n    if( in32 & 0xFFFF0000 ) {\n        return SKP_Silk_CLZ16((SKP_int16)(in32 >> 16));\n    } else {\n        return SKP_Silk_CLZ16((SKP_int16)in32) + 16;\n    }\n}\n\n#endif //_SKP_SILK_API_C_H_\n\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_macros_arm.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef _SKP_SILK_API_ARM_H_\n#define _SKP_SILK_API_ARM_H_\n\n// This is an inline header file for embedded arm platform.\n\n#if EMBEDDED_ARM==4\nextern SKP_int32 SKP_Silk_CLZ16(SKP_int16 in16);\nextern SKP_int32 SKP_Silk_CLZ32(SKP_int32 in32);\n\n// (a32 * (SKP_int32)((SKP_int16)(b32))) >> 16\n#define SKP_SMULWB(a32, b32)\t\t\t((((a32) >> 16) * (SKP_int32)((SKP_int16)(b32))) + ((((a32) & 0x0000FFFF) * (SKP_int32)((SKP_int16)(b32))) >> 16))\n\n// a32 + (b32 * (SKP_int32)((SKP_int16)(c32))) >> 16\n#define SKP_SMLAWB(a32, b32, c32)\t\t((a32) + ((((b32) >> 16) * (SKP_int32)((SKP_int16)(c32))) + ((((b32) & 0x0000FFFF) * (SKP_int32)((SKP_int16)(c32))) >> 16)))\n\n/*SKP_INLINE SKP_int32 SKP_SMULWT(SKP_int32 a32, SKP_int32 b32)\n{\n\tSKP_int32 out32, tmp; \n\tSKP_int32 tmp32=0xFFFF0000;\n\tasm volatile(\"and %1, %3, %4 \\n\\t smull %3, %0, %2, %1\" : \"=&r\" (out32), \"=&r\" (tmp) : \"r\" (a32), \"r\" (b32), \"r\" (tmp32));\n\treturn(out32);\n}*/\n\n// (a32 * (b32 >> 16)) >> 16\n#define SKP_SMULWT(a32, b32)\t\t\t(((a32) >> 16) * ((b32) >> 16) + ((((a32) & 0x0000FFFF) * ((b32) >> 16)) >> 16))\n\n// a32 + (b32 * (c32 >> 16)) >> 16\n#define SKP_SMLAWT(a32, b32, c32)\t\t((a32) + (((b32) >> 16) * ((c32) >> 16)) + ((((b32) & 0x0000FFFF) * ((c32) >> 16)) >> 16))\n\n// (SKP_int32)((SKP_int16)(a3))) * (SKP_int32)((SKP_int16)(b32))\n#define SKP_SMULBB(a32, b32)\t\t\t((SKP_int32)((SKP_int16)(a32)) * (SKP_int32)((SKP_int16)(b32)))\n\n// a32 + (SKP_int32)((SKP_int16)(b32)) * (SKP_int32)((SKP_int16)(c32))\n#define SKP_SMLABB(a32, b32, c32)\t\t((a32) + ((SKP_int32)((SKP_int16)(b32))) * (SKP_int32)((SKP_int16)(c32)))\n\n// a32 + (SKP_int32)((SKP_int16)(b32)) * (SKP_int32)((SKP_int16)(c32))\n#define SKP_SMLABB_ovflw(a32, b32, c32)\t((a32) + ((SKP_int32)((SKP_int16)(b32))) * (SKP_int32)((SKP_int16)(c32)))\n\n// (SKP_int32)((SKP_int16)(a32)) * (b32 >> 16)\n#define SKP_SMULBT(a32, b32)\t\t\t((SKP_int32)((SKP_int16)(a32)) * ((b32) >> 16))\n\n// a32 + (SKP_int32)((SKP_int16)(b32)) * (c32 >> 16)\n#define SKP_SMLABT(a32, b32, c32)\t\t((a32) + ((SKP_int32)((SKP_int16)(b32))) * ((c32) >> 16))\n\nSKP_INLINE SKP_int64 SKP_SMLAL(SKP_int64 a64, SKP_int32 b32, SKP_int32 c32)\n{\n#ifdef IPHONE\n    // IPHONE LLVM compiler doesn't understand Q/R representation. \n    a64 = (SKP_int64)b32 * c32;\n    return(a64);\n#else\n\t__asm__ __volatile__ (\"smlal %Q0, %R0, %2, %3\" : \"=r\" (a64) : \"0\" (a64), \"r\" (b32), \"r\" (c32));\t\n\treturn(a64);\n#endif    \n}\n\n// (a32 * b32) >> 16\n#define SKP_SMULWW(a32, b32)\t\t\tSKP_MLA(SKP_SMULWB((a32), (b32)), (a32), SKP_RSHIFT_ROUND((b32), 16))\n\n// a32 + ((b32 * c32) >> 16)\n#define SKP_SMLAWW(a32, b32, c32)\t\tSKP_MLA(SKP_SMLAWB((a32), (b32), (c32)), (b32), SKP_RSHIFT_ROUND((c32), 16))\n\n/* add/subtract with output saturated */\n#define SKP_ADD_SAT32(a, b)\t\t\t\t((((a) + (b)) & 0x80000000) == 0 ?\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t((((a) & (b)) & 0x80000000) != 0 ? SKP_int32_MIN : (a)+(b)) :\t\\\n\t\t\t\t\t\t\t\t\t\t((((a) | (b)) & 0x80000000) == 0 ? SKP_int32_MAX : (a)+(b)) )\n\n#define SKP_SUB_SAT32(a, b)\t\t\t\t((((a)-(b)) & 0x80000000) == 0 ?\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t(( (a) & ((b)^0x80000000) & 0x80000000) ? SKP_int32_MIN : (a)-(b)) :\t\\\n\t\t\t\t\t\t\t\t\t\t((((a)^0x80000000) & (b)  & 0x80000000) ? SKP_int32_MAX : (a)-(b)) )\n\n#define SKP_SMMUL(a32, b32)\t\t\t\t(SKP_int32)SKP_RSHIFT64(SKP_SMULL((a32), (b32)), 32)\n\n\n#else\nSKP_INLINE SKP_int32 SKP_SMULWB(SKP_int32 a32, SKP_int32 b32) {\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smulwb %0, %1, %2\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32));\t\n\treturn(out32);\n}\n\n\nSKP_INLINE SKP_int32 SKP_SMLAWB(SKP_int32 a32, SKP_int32 b32, SKP_int32 c32) {\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smlawb %0, %2, %3, %1\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32), \"r\" (c32));\t\n\treturn(out32);\n}\n\nSKP_INLINE SKP_int32 SKP_SMULWT(SKP_int32 a32, SKP_int32 b32)\n{\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smulwt %0, %1, %2\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32));\n\treturn(out32);\n}\n\nSKP_INLINE SKP_int32 SKP_SMLAWT(SKP_int32 a32, SKP_int32 b32, SKP_int32 c32)\n{\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smlawt %0, %2, %3, %1\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32), \"r\" (c32));\n\treturn(out32);\n}\n\nSKP_INLINE SKP_int32 SKP_SMULBB(SKP_int32 a32, SKP_int32 b32) {\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smulbb %0, %1, %2\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32));\t\n\treturn(out32);\n}\n\nSKP_INLINE SKP_int32 SKP_SMLABB(SKP_int32 a32, SKP_int32 b32, SKP_int32 c32) {\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smlabb %0, %2, %3, %1\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32), \"r\" (c32));\t\n\treturn(out32);\n}\n\nSKP_INLINE SKP_int32 SKP_SMLABB_ovflw(SKP_int32 a32, SKP_int32 b32, SKP_int32 c32) {\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smlabb %0, %2, %3, %1\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32), \"r\" (c32));\t\n\treturn(out32);\n}\n\nSKP_INLINE SKP_int32 SKP_SMULBT(SKP_int32 a32, SKP_int32 b32) {\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smulbt %0, %1, %2\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32));\t\n\treturn(out32);\n}\n\nSKP_INLINE SKP_int32 SKP_SMLABT(SKP_int32 a32, SKP_int32 b32, SKP_int32 c32) {\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smlabt %0, %2, %3, %1\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32), \"r\" (c32));\t\n\treturn(out32);\n}\n\nSKP_INLINE SKP_int64 SKP_SMLAL(SKP_int64 a64, SKP_int32 b32, SKP_int32 c32)\n{\n#ifdef IPHONE\n    // IPHONE LLVM compiler doesn't understand Q/R representation. \n    a64 = (SKP_int64)b32 * c32;\n    return(a64);\n#else\n\t__asm__ __volatile__ (\"smlal %Q0, %R0, %2, %3\" : \"=r\" (a64) : \"0\" (a64), \"r\" (b32), \"r\" (c32));\t\n\treturn(a64);\n#endif    \n}\n\n#define SKP_SMULWW(a32, b32)\t\t\tSKP_MLA(SKP_SMULWB((a32), (b32)), (a32), SKP_RSHIFT_ROUND((b32), 16))\n\n/*SKP_INLINE SKP_int32 SKP_SMULWW(SKP_int32 a32, SKP_int32 b32)\n{\n\tSKP_int64 tmp;\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smull %Q1, %R1, %2, %3 \\n\\t mov %0, %R1, lsl #16 \\n\\t add %0, %0, %Q1, lsr #16\" : \"=&r\" (out32), \"=&r\" (tmp) : \"r\" (a32), \"r\" (b32));\t\n\treturn(out32);\n}*/\n#define SKP_SMLAWW(a32, b32, c32)\t\tSKP_MLA(SKP_SMLAWB((a32), (b32), (c32)), (b32), SKP_RSHIFT_ROUND((c32), 16))\n/*SKP_INLINE SKP_int32 SKP_SMLAWW(a32, b32, c32){\n\tSKP_int64 tmp;\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smull %Q1, %R1, %3, %4 \\n\\t add %0, %2, %R1, lsl #16 \\n\\t add %0, %0, %Q1, lsr #16\" : \"=&r\" (out32), \"=&r\" (tmp) : \"r\" (a32), \"r\" (b32), \"r\" (c32));\t\n\treturn(out32);\n}*/\n\nSKP_INLINE SKP_int32 SKP_ADD_SAT32(SKP_int32 a32, SKP_int32 b32) {\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"qadd %0, %1, %2\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32));\t\n\treturn(out32);\n}\n\nSKP_INLINE SKP_int32 SKP_SUB_SAT32(SKP_int32 a32, SKP_int32 b32) {\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"qsub %0, %1, %2\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32));\t\n\treturn(out32);\n}\n\nSKP_INLINE SKP_int32 SKP_Silk_CLZ16(SKP_int16 in16)\n{\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"movs %0, %1, lsl #16 \\n\\tclz %0, %0 \\n\\t it eq \\n\\t moveq %0, #16\" : \"=r\" (out32) : \"r\" (in16) : \"cc\");\t\n\treturn(out32);\n}\n\nSKP_INLINE SKP_int32 SKP_Silk_CLZ32(SKP_int32 in32)\n{\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"clz %0, %1\" : \"=r\" (out32) : \"r\" (in32));\t\n\treturn(out32);\n}\n#if EMBEDDED_ARM < 6\n#define SKP_SMMUL(a32, b32)\t\t\t\t(SKP_int32)SKP_RSHIFT64(SKP_SMULL((a32), (b32)), 32)\n#endif\n#endif\n\n// Some ARMv6 specific instructions:\n\n#if EMBEDDED_ARM>=6\n\nSKP_INLINE SKP_int32 SKP_SMMUL(SKP_int32 a32, SKP_int32 b32){\t\t\t\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smmul %0, %1, %2\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32));\t\n\treturn(out32);\n}\n\nSKP_INLINE SKP_int32 SKP_SMUAD(SKP_int32 a32, SKP_int32 b32)\n{\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smuad %0, %1, %2\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32));\n\treturn(out32);\n}\n\nSKP_INLINE SKP_int32 SKP_SMLAD(SKP_int32 a32, SKP_int32 b32, SKP_int32 c32)\n{\n\tSKP_int32 out32;\n\t__asm__ __volatile__ (\"smlad %0, %2, %3, %1\" : \"=r\" (out32) : \"r\" (a32), \"r\" (b32), \"r\" (c32));\n\treturn(out32);\n}\n\n#endif\n\n#endif // _SKP_SILK_API_ARM_H_\n\n\n\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_main.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_MAIN_H\n#define SKP_SILK_MAIN_H\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n#include \"SKP_Silk_define.h\"\n#include \"SKP_Silk_structs.h\"\n#include \"SKP_Silk_tables.h\"\n#include \"SKP_Silk_PLC.h\"\n\n\n/* Encodes signs of excitation */\nvoid SKP_Silk_encode_signs(\n    SKP_Silk_range_coder_state  *psRC,              /* I/O  Range coder state                           */\n    const SKP_int8              q[],                /* I    pulse signal                                */\n    const SKP_int               length,             /* I    length of input                             */\n    const SKP_int               sigtype,            /* I    Signal type                                 */\n    const SKP_int               QuantOffsetType,    /* I    Quantization offset type                    */\n    const SKP_int               RateLevelIndex      /* I    Rate Level Index                            */\n);\n\n/* Decodes signs of excitation */\nvoid SKP_Silk_decode_signs(\n    SKP_Silk_range_coder_state  *psRC,              /* I/O  Range coder state                           */\n    SKP_int                     q[],                /* I/O  pulse signal                                */\n    const SKP_int               length,             /* I    length of output                            */\n    const SKP_int               sigtype,            /* I    Signal type                                 */\n    const SKP_int               QuantOffsetType,    /* I    Quantization offset type                    */\n    const SKP_int               RateLevelIndex      /* I    Rate Level Index                            */\n);\n\n/* Control internal sampling rate */\nSKP_int SKP_Silk_control_audio_bandwidth(\n    SKP_Silk_encoder_state      *psEncC,            /* I/O  Pointer to Silk encoder state               */\n    const SKP_int32             TargetRate_bps      /* I    Target max bitrate (bps)                    */\n);\n\n/***************/\n/* Shell coder */\n/***************/\n\n/* Encode quantization indices of excitation */\nvoid SKP_Silk_encode_pulses(\n    SKP_Silk_range_coder_state  *psRC,              /* I/O  Range coder state                           */\n    const SKP_int               sigtype,            /* I    Sigtype                                     */\n    const SKP_int               QuantOffsetType,    /* I    QuantOffsetType                             */\n    const SKP_int8              q[],                /* I    quantization indices                        */\n    const SKP_int               frame_length        /* I    Frame length                                */\n);\n\n/* Shell encoder, operates on one shell code frame of 16 pulses */\nvoid SKP_Silk_shell_encoder(\n    SKP_Silk_range_coder_state  *psRC,              /* I/O  compressor data structure                   */\n    const SKP_int               *pulses0            /* I    data: nonnegative pulse amplitudes          */\n);\n\n/* Shell decoder, operates on one shell code frame of 16 pulses */\nvoid SKP_Silk_shell_decoder(\n    SKP_int                     *pulses0,           /* O    data: nonnegative pulse amplitudes          */\n    SKP_Silk_range_coder_state  *psRC,              /* I/O  compressor data structure                   */\n    const SKP_int               pulses4             /* I    number of pulses per pulse-subframe         */\n);\n\n/***************/\n/* Range coder */\n/***************/\n/* Range encoder for one symbol */\nvoid SKP_Silk_range_encoder(\n    SKP_Silk_range_coder_state  *psRC,              /* I/O  compressor data structure                   */\n    const SKP_int               data,               /* I    uncompressed data                           */\n    const SKP_uint16            prob[]              /* I    cumulative density functions                */\n);\n    \n/* Range encoder for multiple symbols */\nvoid SKP_Silk_range_encoder_multi(\n    SKP_Silk_range_coder_state  *psRC,              /* I/O  compressor data structure                   */\n    const SKP_int               data[],             /* I    uncompressed data    [nSymbols]             */\n    const SKP_uint16 * const    prob[],             /* I    cumulative density functions                */\n    const SKP_int               nSymbols            /* I    number of data symbols                      */\n);\n\n/* Range decoder for one symbol */\nvoid SKP_Silk_range_decoder(\n    SKP_int                     data[],             /* O    uncompressed data                           */\n    SKP_Silk_range_coder_state  *psRC,              /* I/O  compressor data structure                   */\n    const SKP_uint16            prob[],             /* I    cumulative density function                 */\n    SKP_int                     probIx              /* I    initial (middle) entry of cdf               */\n);\n\n/* Range decoder for multiple symbols */\nvoid SKP_Silk_range_decoder_multi(\n    SKP_int                     data[],             /* O    uncompressed data                [nSymbols] */\n    SKP_Silk_range_coder_state  *psRC,              /* I/O  compressor data structure                   */\n    const SKP_uint16 * const    prob[],             /* I    cumulative density functions                */\n    const SKP_int               probStartIx[],      /* I    initial (middle) entries of cdfs [nSymbols] */\n    const SKP_int               nSymbols            /* I    number of data symbols                      */\n);\n\n/* Initialize range coder structure for encoder */\nvoid SKP_Silk_range_enc_init(\n    SKP_Silk_range_coder_state  *psRC               /* O    compressor data structure                   */\n);\n\n/* Initialize range coder structure for decoder */\nvoid SKP_Silk_range_dec_init(\n    SKP_Silk_range_coder_state  *psRC,              /* O    compressor data structure                   */\n    const SKP_uint8             buffer[],           /* I    buffer for compressed data [bufferLength]   */\n    const SKP_int32             bufferLength        /* I    buffer length (in bytes)                    */\n);\n\n/* Determine length of bitstream */\nSKP_int SKP_Silk_range_coder_get_length(            /* O    returns number of BITS in stream            */\n    const SKP_Silk_range_coder_state    *psRC,      /* I    compressed data structure                   */\n    SKP_int                             *nBytes     /* O    number of BYTES in stream                   */\n);\n\n/* Write decodable stream to buffer, and determine its length */\nvoid SKP_Silk_range_enc_wrap_up(\n    SKP_Silk_range_coder_state  *psRC               /* I/O  compressed data structure                   */\n);\n\n/* Check that any remaining bits in the last byte are set to 1 */\nvoid SKP_Silk_range_coder_check_after_decoding(\n    SKP_Silk_range_coder_state  *psRC               /* I/O  compressed data structure                   */\n);\n\n/* Gain scalar quantization with hysteresis, uniform on log scale */\nvoid SKP_Silk_gains_quant(\n    SKP_int                     ind[ NB_SUBFR ],        /* O    gain indices                            */\n    SKP_int32                   gain_Q16[ NB_SUBFR ],   /* I/O  gains (quantized out)                   */\n    SKP_int                     *prev_ind,              /* I/O  last index in previous frame            */\n    const SKP_int               conditional             /* I    first gain is delta coded if 1          */\n);\n\n/* Gains scalar dequantization, uniform on log scale */\nvoid SKP_Silk_gains_dequant(\n    SKP_int32                   gain_Q16[ NB_SUBFR ],   /* O    quantized gains                         */\n    const SKP_int               ind[ NB_SUBFR ],        /* I    gain indices                            */\n    SKP_int                     *prev_ind,              /* I/O  last index in previous frame            */\n    const SKP_int               conditional             /* I    first gain is delta coded if 1          */\n);\n\n/* Convert NLSF parameters to stable AR prediction filter coefficients */\nvoid SKP_Silk_NLSF2A_stable(\n    SKP_int16                   pAR_Q12[ MAX_LPC_ORDER ],   /* O    Stabilized AR coefs [LPC_order]     */ \n    const SKP_int               pNLSF[ MAX_LPC_ORDER ],     /* I    NLSF vector         [LPC_order]     */\n    const SKP_int               LPC_order                   /* I    LPC/LSF order                       */\n);\n\n/* Interpolate two vectors */\nvoid SKP_Silk_interpolate(\n    SKP_int                     xi[ MAX_LPC_ORDER ],    /* O    interpolated vector                     */\n    const SKP_int               x0[ MAX_LPC_ORDER ],    /* I    first vector                            */\n    const SKP_int               x1[ MAX_LPC_ORDER ],    /* I    second vector                           */\n    const SKP_int               ifact_Q2,               /* I    interp. factor, weight on 2nd vector    */\n    const SKP_int               d                       /* I    number of parameters                    */\n);\n\n/***********************************/\n/* Noise shaping quantization (NSQ)*/\n/***********************************/\nvoid SKP_Silk_NSQ(\n    SKP_Silk_encoder_state          *psEncC,                                    /* I/O  Encoder State                       */\n    SKP_Silk_encoder_control        *psEncCtrlC,                                /* I    Encoder Control                     */\n    SKP_Silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                           */\n    const SKP_int16                 x[],                                        /* I    prefiltered input signal            */\n    SKP_int8                        q[],                                        /* O    quantized qulse signal              */\n    const SKP_int                   LSFInterpFactor_Q2,                         /* I    LSF interpolation factor in Q2      */\n    const SKP_int16                 PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Short term prediction coefficients  */\n    const SKP_int16                 LTPCoef_Q14[ LTP_ORDER * NB_SUBFR ],        /* I    Long term prediction coefficients   */\n    const SKP_int16                 AR2_Q13[ NB_SUBFR * MAX_SHAPE_LPC_ORDER ],  /* I                                        */\n    const SKP_int                   HarmShapeGain_Q14[ NB_SUBFR ],              /* I                                        */\n    const SKP_int                   Tilt_Q14[ NB_SUBFR ],                       /* I    Spectral tilt                       */\n    const SKP_int32                 LF_shp_Q14[ NB_SUBFR ],                     /* I                                        */\n    const SKP_int32                 Gains_Q16[ NB_SUBFR ],                      /* I                                        */\n    const SKP_int                   Lambda_Q10,                                 /* I                                        */\n    const SKP_int                   LTP_scale_Q14                               /* I    LTP state scaling                   */\n);\n\n/* Noise shaping using delayed decision */\nvoid SKP_Silk_NSQ_del_dec(\n    SKP_Silk_encoder_state          *psEncC,                                    /* I/O  Encoder State                       */\n    SKP_Silk_encoder_control        *psEncCtrlC,                                /* I    Encoder Control                     */\n    SKP_Silk_nsq_state              *NSQ,                                       /* I/O  NSQ state                           */\n    const SKP_int16                 x[],                                        /* I    Prefiltered input signal            */\n    SKP_int8                        q[],                                        /* O    Quantized pulse signal              */\n    const SKP_int                   LSFInterpFactor_Q2,                         /* I    LSF interpolation factor in Q2      */\n    const SKP_int16                 PredCoef_Q12[ 2 * MAX_LPC_ORDER ],          /* I    Prediction coefs                    */\n    const SKP_int16                 LTPCoef_Q14[ LTP_ORDER * NB_SUBFR ],        /* I    LT prediction coefs                 */\n    const SKP_int16                 AR2_Q13[ NB_SUBFR * MAX_SHAPE_LPC_ORDER ],  /* I                                        */\n    const SKP_int                   HarmShapeGain_Q14[ NB_SUBFR ],              /* I                                        */\n    const SKP_int                   Tilt_Q14[ NB_SUBFR ],                       /* I    Spectral tilt                       */\n    const SKP_int32                 LF_shp_Q14[ NB_SUBFR ],                     /* I                                        */\n    const SKP_int32                 Gains_Q16[ NB_SUBFR ],                      /* I                                        */\n    const SKP_int                   Lambda_Q10,                                 /* I                                        */\n    const SKP_int                   LTP_scale_Q14                               /* I    LTP state scaling                   */\n);\n\n/************/\n/* Silk VAD */\n/************/\n/* Initialize the Silk VAD */\nSKP_int SKP_Silk_VAD_Init(                          /* O    Return value, 0 if success                  */ \n    SKP_Silk_VAD_state          *psSilk_VAD         /* I/O  Pointer to Silk VAD state                   */ \n); \n\n/* Silk VAD noise level estimation */\nvoid SKP_Silk_VAD_GetNoiseLevels(\n    const SKP_int32             pX[ VAD_N_BANDS ],  /* I    subband energies                            */\n    SKP_Silk_VAD_state          *psSilk_VAD         /* I/O  Pointer to Silk VAD state                   */ \n);\n\n/* Get speech activity level in Q8 */\nSKP_int SKP_Silk_VAD_GetSA_Q8(                                  /* O    Return value, 0 if success      */\n    SKP_Silk_VAD_state          *psSilk_VAD,                    /* I/O  Silk VAD state                  */\n    SKP_int                     *pSA_Q8,                        /* O    Speech activity level in Q8     */\n    SKP_int                     *pSNR_dB_Q7,                    /* O    SNR for current frame in Q7     */\n    SKP_int                     pQuality_Q15[ VAD_N_BANDS ],    /* O    Smoothed SNR for each band      */\n    SKP_int                     *pTilt_Q15,                     /* O    current frame's frequency tilt  */\n    const SKP_int16             pIn[],                          /* I    PCM input       [framelength]   */\n    const SKP_int               framelength                     /* I    Input frame length              */\n);\n\n/* Detect signal in 8 - 12 khz range */\nvoid SKP_Silk_detect_SWB_input(\n    SKP_Silk_detect_SWB_state   *psSWBdetect,       /* I/O  Encoder state                               */\n    const SKP_int16             samplesIn[],        /* I    Input to encoder                            */\n    SKP_int                     nSamplesIn          /* I    Length of input                             */\n);\n\n#if SWITCH_TRANSITION_FILTERING\n/* Low-pass filter with variable cutoff frequency based on  */\n/* piece-wise linear interpolation between elliptic filters */\n/* Start by setting transition_frame_no = 1;                */\nvoid SKP_Silk_LP_variable_cutoff(\n    SKP_Silk_LP_state           *psLP,              /* I/O  LP filter state                             */\n    SKP_int16                   *out,               /* O    Low-pass filtered output signal             */\n    const SKP_int16             *in,                /* I    Input signal                                */\n    const SKP_int               frame_length        /* I    Frame length                                */\n);\n#endif\n\n/****************************************************/\n/* Decoder Functions                                */\n/****************************************************/\nSKP_int SKP_Silk_create_decoder(\n    SKP_Silk_decoder_state      **ppsDec            /* I/O  Decoder state pointer pointer               */\n);\n\nSKP_int SKP_Silk_free_decoder(\n    SKP_Silk_decoder_state      *psDec              /* I/O  Decoder state pointer                       */\n);\n\nSKP_int SKP_Silk_init_decoder(\n    SKP_Silk_decoder_state      *psDec              /* I/O  Decoder state pointer                       */\n);\n\n/* Set decoder sampling rate */\nvoid SKP_Silk_decoder_set_fs(\n    SKP_Silk_decoder_state      *psDec,             /* I/O  Decoder state pointer                       */\n    SKP_int                     fs_kHz              /* I    Sampling frequency (kHz)                    */\n);\n\n/****************/\n/* Decode frame */\n/****************/\nSKP_int SKP_Silk_decode_frame(\n    SKP_Silk_decoder_state      *psDec,             /* I/O  Pointer to Silk decoder state               */\n    SKP_int16                   pOut[],             /* O    Pointer to output speech frame              */\n    SKP_int16                   *pN,                /* O    Pointer to size of output frame             */\n    const SKP_uint8             pCode[],            /* I    Pointer to payload                          */\n    const SKP_int               nBytes,             /* I    Payload length                              */\n    SKP_int                     action,             /* I    Action from Jitter Buffer                   */\n    SKP_int                     *decBytes           /* O    Used bytes to decode this frame             */\n);\n\n/* Decode parameters from payload */\nvoid SKP_Silk_decode_parameters(\n    SKP_Silk_decoder_state      *psDec,             /* I/O  State                                       */\n    SKP_Silk_decoder_control    *psDecCtrl,         /* I/O  Decoder control                             */\n    SKP_int                     q[],                /* O    Excitation signal                           */\n    const SKP_int               fullDecoding        /* I    Flag to tell if only arithmetic decoding    */\n);\n\n/* Core decoder. Performs inverse NSQ operation LTP + LPC */\nvoid SKP_Silk_decode_core(\n    SKP_Silk_decoder_state      *psDec,                             /* I/O  Decoder state               */\n    SKP_Silk_decoder_control    *psDecCtrl,                         /* I    Decoder control             */\n    SKP_int16                   xq[],                               /* O    Decoded speech              */\n    const SKP_int               q[ MAX_FRAME_LENGTH ]               /* I    Pulse signal                */\n);\n\n/* NLSF vector decoder */\nvoid SKP_Silk_NLSF_MSVQ_decode(\n    SKP_int                         *pNLSF_Q15,     /* O    Pointer to decoded output [LPC_ORDER x 1]   */\n    const SKP_Silk_NLSF_CB_struct   *psNLSF_CB,     /* I    Pointer to NLSF codebook struct             */\n    const SKP_int                   *NLSFIndices,   /* I    Pointer to NLSF indices [nStages x 1]       */\n    const SKP_int                   LPC_order       /* I    LPC order                                   */\n);\n\n/**********************/\n/* Arithmetic coding */\n/*********************/\n\n/* Decode quantization indices of excitation (Shell coding) */\nvoid SKP_Silk_decode_pulses(\n    SKP_Silk_range_coder_state  *psRC,              /* I/O  Range coder state                           */\n    SKP_Silk_decoder_control    *psDecCtrl,         /* I/O  Decoder control                             */\n    SKP_int                     q[],                /* O    Excitation signal                           */\n    const SKP_int               frame_length        /* I    Frame length (preliminary)                  */\n);\n\n/******************/\n/* CNG */\n/******************/\n\n/* Reset CNG */\nvoid SKP_Silk_CNG_Reset(\n    SKP_Silk_decoder_state      *psDec              /* I/O  Decoder state                               */\n);\n\n/* Updates CNG estimate, and applies the CNG when packet was lost   */\nvoid SKP_Silk_CNG(\n    SKP_Silk_decoder_state      *psDec,             /* I/O  Decoder state                               */\n    SKP_Silk_decoder_control    *psDecCtrl,         /* I/O  Decoder control                             */\n    SKP_int16                   signal[],           /* I/O  Signal                                      */\n    SKP_int                     length              /* I    Length of residual                          */\n);\n\n/* Encoding of various parameters */\nvoid SKP_Silk_encode_parameters(\n    SKP_Silk_encoder_state      *psEncC,            /* I/O  Encoder state                               */\n    SKP_Silk_encoder_control    *psEncCtrlC,        /* I/O  Encoder control                             */\n    SKP_Silk_range_coder_state  *psRC,              /* I/O  Range coder state                           */\n    const SKP_int8               *q                 /* I    Quantization indices                        */\n);\n\n/* Extract lowest layer encoding */\nvoid SKP_Silk_get_low_layer_internal(\n    const SKP_uint8             *indata,            /* I:   Encoded input vector                        */\n    const SKP_int16             nBytesIn,           /* I:   Number of input Bytes                       */\n    SKP_uint8                   *Layer0data,        /* O:   Layer0 payload                              */\n    SKP_int16                   *nLayer0Bytes       /* O:   Number of FEC Bytes                         */\n);\n\n/* Resets LBRR buffer, used if packet size changes */\nvoid SKP_Silk_LBRR_reset( \n    SKP_Silk_encoder_state      *psEncC             /* I/O  Pointer to Silk encoder state               */\n);\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_main_FIX.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_MAIN_FIX_H\n#define SKP_SILK_MAIN_FIX_H\n\n#include <stdlib.h>\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_structs_FIX.h\"\n#include \"SKP_Silk_main.h\"\n#include \"SKP_Silk_PLC.h\"\n#define TIC(TAG_NAME)\n#define TOC(TAG_NAME)\n\n#ifndef FORCE_CPP_BUILD\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n#endif\n\n/*********************/\n/* Encoder Functions */\n/*********************/\n\n/* Initializes the Silk encoder state */\nSKP_int SKP_Silk_init_encoder_FIX(\n    SKP_Silk_encoder_state_FIX  *psEnc                  /* I/O  Pointer to Silk FIX encoder state       */\n);\n\n/* Control the Silk encoder */\nSKP_int SKP_Silk_control_encoder_FIX( \n    SKP_Silk_encoder_state_FIX  *psEnc,                 /* I/O  Pointer to Silk encoder state           */\n    const SKP_int               PacketSize_ms,          /* I    Packet length (ms)                      */\n    const SKP_int32             TargetRate_bps,         /* I    Target max bitrate (bps)                */\n    const SKP_int               PacketLoss_perc,        /* I    Packet loss rate (in percent)           */\n    const SKP_int               DTX_enabled,            /* I    Enable / disable DTX                    */\n    const SKP_int               Complexity              /* I    Complexity (0->low; 1->medium; 2->high) */\n);\n\n/* Encoder main function */\nSKP_int SKP_Silk_encode_frame_FIX( \n    SKP_Silk_encoder_state_FIX      *psEnc,             /* I/O  Pointer to Silk FIX encoder state           */\n    SKP_uint8                       *pCode,             /* O    Pointer to payload                          */\n    SKP_int16                       *pnBytesOut,        /* I/O  Pointer to number of payload bytes;         */\n                                                        /*      input: max length; output: used             */\n    const SKP_int16                 *pIn                /* I    Pointer to input speech frame               */\n);\n\n/* Low BitRate Redundancy encoding functionality. Reuse all parameters but encode with lower bitrate */\nvoid SKP_Silk_LBRR_encode_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,         /* I/O  Pointer to Silk FIX encoder state           */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl,     /* I/O  Pointer to Silk FIX encoder control struct  */\n    SKP_uint8                       *pCode,         /* O    Pointer to payload                          */\n    SKP_int16                       *pnBytesOut,    /* I/O  Pointer to number of payload bytes          */\n    SKP_int16                       xfw[]           /* I    Input signal                                */\n);\n\n/* High-pass filter with cutoff frequency adaptation based on pitch lag statistics */\nvoid SKP_Silk_HP_variable_cutoff_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,         /* I/O  Encoder state                               */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl,     /* I/O  Encoder control                             */\n    SKP_int16                       *out,           /* O    high-pass filtered output signal            */\n    const SKP_int16                 *in             /* I    input signal                                */\n);\n\n/****************/\n/* Prefiltering */\n/****************/\nvoid SKP_Silk_prefilter_FIX(\n    SKP_Silk_encoder_state_FIX          *psEnc,         /* I/O  Encoder state                               */\n    const SKP_Silk_encoder_control_FIX  *psEncCtrl,     /* I    Encoder control                             */\n    SKP_int16                           xw[],           /* O    Weighted signal                             */\n    const SKP_int16                     x[]             /* I    Speech signal                               */\n);\n\n/**************************************************************/\n/* Compute noise shaping coefficients and initial gain values */\n/**************************************************************/\nvoid SKP_Silk_noise_shape_analysis_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,         /* I/O  Encoder state FIX                           */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl,     /* I/O  Encoder control FIX                         */\n    const SKP_int16                 *pitch_res,     /* I    LPC residual from pitch analysis            */\n    const SKP_int16                 *x              /* I    Input signal [ frame_length + la_shape ]    */\n);\n\n/* Autocorrelations for a warped frequency axis */\nvoid SKP_Silk_warped_autocorrelation_FIX(\n          SKP_int32                 *corr,              /* O    Result [order + 1]                      */\n          SKP_int                   *scale,             /* O    Scaling of the correlation vector       */\n    const SKP_int16                 *input,             /* I    Input data to correlate                 */\n    const SKP_int16                 warping_Q16,        /* I    Warping coefficient                     */\n    const SKP_int                   length,             /* I    Length of input                         */\n    const SKP_int                   order               /* I    Correlation order (even)                */\n);\n\n/* Processing of gains */\nvoid SKP_Silk_process_gains_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,         /* I/O  Encoder state                               */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl      /* I/O  Encoder control                             */\n);\n\n/* Control low bitrate redundancy usage */\nvoid SKP_Silk_LBRR_ctrl_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,         /* I/O  encoder state                               */\n    SKP_Silk_encoder_control        *psEncCtrlC     /* I/O  encoder control                             */\n);\n\n/* Calculation of LTP state scaling */\nvoid SKP_Silk_LTP_scale_ctrl_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,         /* I/O  encoder state                               */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl      /* I/O  encoder control                             */\n);\n\n/**********************************************/\n/* Prediction Analysis                        */\n/**********************************************/\n\n/* Find pitch lags */\nvoid SKP_Silk_find_pitch_lags_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,         /* I/O  encoder state                               */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl,     /* I/O  encoder control                             */\n    SKP_int16                       res[],          /* O    residual                                    */\n    const SKP_int16                 x[]             /* I    Speech signal                               */\n);\n\nvoid SKP_Silk_find_pred_coefs_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,         /* I/O  encoder state                               */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl,     /* I/O  encoder control                             */\n    const SKP_int16                 res_pitch[]     /* I    Residual from pitch analysis                */\n);\n\nvoid SKP_Silk_find_LPC_FIX(\n    SKP_int             NLSF_Q15[],             /* O    NLSFs                                                                       */\n    SKP_int             *interpIndex,           /* O    NLSF interpolation index, only used for NLSF interpolation                  */\n    const SKP_int       prev_NLSFq_Q15[],       /* I    previous NLSFs, only used for NLSF interpolation                            */\n    const SKP_int       useInterpolatedLSFs,    /* I    Flag                                                                        */\n    const SKP_int       LPC_order,              /* I    LPC order                                                                   */\n    const SKP_int16     x[],                    /* I    Input signal                                                                */\n    const SKP_int       subfr_length            /* I    Input signal subframe length including preceeding samples                   */\n);\n\nvoid SKP_Silk_warped_LPC_analysis_filter_FIX(\n          SKP_int32                 state[],            /* I/O  State [order + 1]                       */\n          SKP_int16                 res[],              /* O    Residual signal [length]                */\n    const SKP_int16                 coef_Q13[],         /* I    Coefficients [order]                    */\n    const SKP_int16                 input[],            /* I    Input signal [length]                   */\n    const SKP_int16                 lambda_Q16,         /* I    Warping factor                          */\n    const SKP_int                   length,             /* I    Length of input signal                  */\n    const SKP_int                   order               /* I    Filter order (even)                     */\n);\n\nvoid SKP_Silk_LTP_analysis_filter_FIX(\n    SKP_int16       *LTP_res,                           /* O:   LTP residual signal of length NB_SUBFR * ( pre_length + subfr_length )  */\n    const SKP_int16 *x,                                 /* I:   Pointer to input signal with at least max( pitchL ) preceeding samples  */\n    const SKP_int16 LTPCoef_Q14[ LTP_ORDER * NB_SUBFR ],/* I:   LTP_ORDER LTP coefficients for each NB_SUBFR subframe                   */\n    const SKP_int   pitchL[ NB_SUBFR ],                 /* I:   Pitch lag, one for each subframe                                        */\n    const SKP_int32 invGains_Q16[ NB_SUBFR ],           /* I:   Inverse quantization gains, one for each subframe                       */\n    const SKP_int   subfr_length,                       /* I:   Length of each subframe                                                 */\n    const SKP_int   pre_length                          /* I:   Length of the preceeding samples starting at &x[0] for each subframe    */\n);\n\n/* Finds LTP vector from correlations */\nvoid SKP_Silk_find_LTP_FIX(\n    SKP_int16           b_Q14[ NB_SUBFR * LTP_ORDER ],              /* O    LTP coefs                                                   */\n    SKP_int32           WLTP[ NB_SUBFR * LTP_ORDER * LTP_ORDER ],   /* O    Weight for LTP quantization                                 */\n    SKP_int             *LTPredCodGain_Q7,                          /* O    LTP coding gain                                             */\n    const SKP_int16     r_first[],                                  /* I    residual signal after LPC signal + state for first 10 ms    */\n    const SKP_int16     r_last[],                                   /* I    residual signal after LPC signal + state for last 10 ms     */\n    const SKP_int       lag[ NB_SUBFR ],                            /* I    LTP lags                                                    */\n    const SKP_int32     Wght_Q15[ NB_SUBFR ],                       /* I    weights                                                     */\n    const SKP_int       subfr_length,                               /* I    subframe length                                             */\n    const SKP_int       mem_offset,                                 /* I    number of samples in LTP memory                             */\n    SKP_int             corr_rshifts[ NB_SUBFR ]                    /* O    right shifts applied to correlations                        */\n);\n\n/* LTP tap quantizer */\nvoid SKP_Silk_quant_LTP_gains_FIX(\n    SKP_int16               B_Q14[],                /* I/O  (un)quantized LTP gains     */\n    SKP_int                 cbk_index[],            /* O    Codebook Index              */\n    SKP_int                 *periodicity_index,     /* O    Periodicity Index           */\n    const SKP_int32         W_Q18[],                /* I    Error Weights in Q18        */\n    SKP_int                 mu_Q8,                  /* I    Mu value (R/D tradeoff)     */\n    SKP_int                 lowComplexity           /* I    Flag for low complexity     */\n);\n\n/******************/\n/* NLSF Quantizer */\n/******************/\n\n/* Limit, stabilize, convert and quantize NLSFs.    */ \nvoid SKP_Silk_process_NLSFs_FIX(\n    SKP_Silk_encoder_state_FIX      *psEnc,     /* I/O  encoder state                               */\n    SKP_Silk_encoder_control_FIX    *psEncCtrl, /* I/O  encoder control                             */\n    SKP_int                         *pNLSF_Q15  /* I/O  Normalized LSFs (quant out) (0 - (2^15-1))  */\n);\n\n/* NLSF vector encoder */\nvoid SKP_Silk_NLSF_MSVQ_encode_FIX(\n          SKP_int                   *NLSFIndices,           /* O    Codebook path vector [ CB_STAGES ]      */\n          SKP_int                   *pNLSF_Q15,             /* I/O  Quantized NLSF vector [ LPC_ORDER ]     */\n    const SKP_Silk_NLSF_CB_struct   *psNLSF_CB,             /* I    Codebook object                         */\n    const SKP_int                   *pNLSF_q_Q15_prev,      /* I    Prev. quantized NLSF vector [LPC_ORDER] */\n    const SKP_int                   *pW_Q6,                 /* I    NLSF weight vector [ LPC_ORDER ]        */\n    const SKP_int                   NLSF_mu_Q15,            /* I    Rate weight for the RD optimization     */\n    const SKP_int                   NLSF_mu_fluc_red_Q16,   /* I    Fluctuation reduction error weight      */\n    const SKP_int                   NLSF_MSVQ_Survivors,    /* I    Max survivors from each stage           */\n    const SKP_int                   LPC_order,              /* I    LPC order                               */\n    const SKP_int                   deactivate_fluc_red     /* I    Deactivate fluctuation reduction        */\n);\n\n/* Rate-Distortion calculations for multiple input data vectors */\nvoid SKP_Silk_NLSF_VQ_rate_distortion_FIX(\n    SKP_int32                       *pRD_Q20,           /* O    Rate-distortion values [psNLSF_CBS->nVectors*N] */\n    const SKP_Silk_NLSF_CBS         *psNLSF_CBS,        /* I    NLSF codebook stage struct                      */\n    const SKP_int                   *in_Q15,            /* I    Input vectors to be quantized                   */\n    const SKP_int                   *w_Q6,              /* I    Weight vector                                   */\n    const SKP_int32                 *rate_acc_Q5,       /* I    Accumulated rates from previous stage           */\n    const SKP_int                   mu_Q15,             /* I    Weight between weighted error and rate          */\n    const SKP_int                   N,                  /* I    Number of input vectors to be quantized         */\n    const SKP_int                   LPC_order           /* I    LPC order                                       */\n);\n\n/* Compute weighted quantization errors for an LPC_order element input vector, over one codebook stage */\nvoid SKP_Silk_NLSF_VQ_sum_error_FIX(\n    SKP_int32                       *err_Q20,           /* O    Weighted quantization errors  [N*K]         */\n    const SKP_int                   *in_Q15,            /* I    Input vectors to be quantized [N*LPC_order] */\n    const SKP_int                   *w_Q6,              /* I    Weighting vectors             [N*LPC_order] */\n    const SKP_int16                 *pCB_Q15,           /* I    Codebook vectors              [K*LPC_order] */\n    const SKP_int                   N,                  /* I    Number of input vectors                     */\n    const SKP_int                   K,                  /* I    Number of codebook vectors                  */\n    const SKP_int                   LPC_order           /* I    Number of LPCs                              */\n);\n\n/* Entropy constrained MATRIX-weighted VQ, for a single input data vector */\nvoid SKP_Silk_VQ_WMat_EC_FIX(\n    SKP_int                         *ind,               /* O    index of best codebook vector               */\n    SKP_int32                       *rate_dist_Q14,     /* O    best weighted quantization error + mu * rate*/\n    const SKP_int16                 *in_Q14,            /* I    input vector to be quantized                */\n    const SKP_int32                 *W_Q18,             /* I    weighting matrix                            */\n    const SKP_int16                 *cb_Q14,            /* I    codebook                                    */\n    const SKP_int16                 *cl_Q6,             /* I    code length for each codebook vector        */\n    const SKP_int                   mu_Q8,              /* I    tradeoff between weighted error and rate    */\n    SKP_int                         L                   /* I    number of vectors in codebook               */\n);\n\n/******************/\n/* Linear Algebra */\n/******************/\n\n/* Calculates correlation matrix X'*X */\nvoid SKP_Silk_corrMatrix_FIX(\n    const SKP_int16                 *x,         /* I    x vector [L + order - 1] used to form data matrix X */\n    const SKP_int                   L,          /* I    Length of vectors                                   */\n    const SKP_int                   order,      /* I    Max lag for correlation                             */\n    const SKP_int                   head_room,  /* I    Desired headroom                                    */\n    SKP_int32                       *XX,        /* O    Pointer to X'*X correlation matrix [ order x order ]*/\n    SKP_int                         *rshifts    /* I/O  Right shifts of correlations                        */\n);\n\n/* Calculates correlation vector X'*t */\nvoid SKP_Silk_corrVector_FIX(\n    const SKP_int16                 *x,         /* I    x vector [L + order - 1] used to form data matrix X */\n    const SKP_int16                 *t,         /* I    Target vector [L]                                   */\n    const SKP_int                   L,          /* I    Length of vectors                                   */\n    const SKP_int                   order,      /* I    Max lag for correlation                             */\n    SKP_int32                       *Xt,        /* O    Pointer to X'*t correlation vector [order]          */\n    const SKP_int                   rshifts     /* I    Right shifts of correlations                        */\n);\n\n/* Add noise to matrix diagonal */\nvoid SKP_Silk_regularize_correlations_FIX(\n    SKP_int32                       *XX,                /* I/O  Correlation matrices                        */\n    SKP_int32                       *xx,                /* I/O  Correlation values                          */\n    SKP_int32                       noise,              /* I    Noise to add                                */\n    SKP_int                         D                   /* I    Dimension of XX                             */\n);\n\n/* Solves Ax = b, assuming A is symmetric */\nvoid SKP_Silk_solve_LDL_FIX(\n    SKP_int32                       *A,                 /* I    Pointer to symetric square matrix A         */\n    SKP_int                         M,                  /* I    Size of matrix                              */\n    const SKP_int32                 *b,                 /* I    Pointer to b vector                         */\n    SKP_int32                       *x_Q16              /* O    Pointer to x solution vector                */\n);\n\n/* Residual energy: nrg = wxx - 2 * wXx * c + c' * wXX * c */\nSKP_int32 SKP_Silk_residual_energy16_covar_FIX(\n    const SKP_int16                 *c,                 /* I    Prediction vector                           */\n    const SKP_int32                 *wXX,               /* I    Correlation matrix                          */\n    const SKP_int32                 *wXx,               /* I    Correlation vector                          */\n    SKP_int32                       wxx,                /* I    Signal energy                               */\n    SKP_int                         D,                  /* I    Dimension                                   */\n    SKP_int                         cQ                  /* I    Q value for c vector 0 - 15                 */\n);\n\n/* Calculates residual energies of input subframes where all subframes have LPC_order   */\n/* of preceeding samples                                                                */\nvoid SKP_Silk_residual_energy_FIX(\n          SKP_int32 nrgs[ NB_SUBFR ],           /* O    Residual energy per subframe    */\n          SKP_int   nrgsQ[ NB_SUBFR ],          /* O    Q value per subframe            */\n    const SKP_int16 x[],                        /* I    Input signal                    */\n          SKP_int16 a_Q12[ 2 ][ MAX_LPC_ORDER ],/* I    AR coefs for each frame half    */\n    const SKP_int32 gains[ NB_SUBFR ],          /* I    Quantization gains              */\n    const SKP_int   subfr_length,               /* I    Subframe length                 */\n    const SKP_int   LPC_order                   /* I    LPC order                       */\n);\n\n#ifndef FORCE_CPP_BUILD\n#ifdef __cplusplus\n}\n#endif /* __cplusplus */\n#endif /* FORCE_CPP_BUILD */\n#endif /* SKP_SILK_MAIN_FIX_H */\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_pitch_est_defines.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SIGPROCFIX_PITCH_EST_DEFINES_H\n#define SIGPROCFIX_PITCH_EST_DEFINES_H\n\n/************************************************************/\n/* Definitions For Fix pitch estimator                      */\n/************************************************************/\n\n#define PITCH_EST_SHORTLAG_BIAS_Q15         6554    /* 0.2f. for logarithmic weighting    */\n#define PITCH_EST_PREVLAG_BIAS_Q15          6554    /* Prev lag bias    */\n#define PITCH_EST_FLATCONTOUR_BIAS_Q20      52429   /* 0.05f */\n\n#endif\n\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_resampler_private.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * File Name:\tSKP_Silk_resampler_structs.h\t\t\t\t\t\t\t*\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * Description: Structs for IIR/FIR resamplers\t\t\t\t\t\t\t*\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n * All rights reserved.\t\t\t\t\t\t\t\t\t\t\t\t\t*\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n *                                                                      */\n\n#ifndef SKP_Silk_RESAMPLER_H\n#define SKP_Silk_RESAMPLER_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_resampler_structs.h\"\n#include \"SKP_Silk_resampler_rom.h\"\n\n/* Number of input samples to process in the inner loop */\n#define RESAMPLER_MAX_BATCH_SIZE_IN             480\n\n/* Description: Hybrid IIR/FIR polyphase implementation of resampling\t*/\nvoid SKP_Silk_resampler_private_IIR_FIR(\n\tvoid\t                        *SS,\t\t    /* I/O: Resampler state \t\t\t\t\t\t*/\n\tSKP_int16\t\t\t\t\t\tout[],\t\t    /* O:\tOutput signal \t\t\t\t\t\t\t*/\n\tconst SKP_int16\t\t\t\t\tin[],\t\t    /* I:\tInput signal\t\t\t\t\t\t\t*/\n\tSKP_int32\t\t\t\t\t    inLen\t\t    /* I:\tNumber of input samples\t\t\t\t\t*/\n);\n\n/* Description: Hybrid IIR/FIR polyphase implementation of resampling\t*/\nvoid SKP_Silk_resampler_private_down_FIR(\n\tvoid\t                        *SS,\t\t    /* I/O: Resampler state \t\t\t\t\t\t*/\n\tSKP_int16\t\t\t\t\t\tout[],\t\t    /* O:\tOutput signal \t\t\t\t\t\t\t*/\n\tconst SKP_int16\t\t\t\t\tin[],\t\t    /* I:\tInput signal\t\t\t\t\t\t\t*/\n\tSKP_int32\t\t\t\t\t    inLen\t\t    /* I:\tNumber of input samples\t\t\t\t\t*/\n);\n\n/* Copy */\nvoid SKP_Silk_resampler_private_copy(\n\tvoid\t                        *SS,\t\t    /* I/O: Resampler state (unused)\t\t\t\t*/\n\tSKP_int16\t\t\t\t\t\tout[],\t\t    /* O:\tOutput signal \t\t\t\t\t\t\t*/\n\tconst SKP_int16\t\t\t\t\tin[],\t\t    /* I:\tInput signal\t\t\t\t\t\t\t*/\n\tSKP_int32\t\t\t\t\t    inLen\t\t    /* I:\tNumber of input samples\t\t\t\t\t*/\n);\n\n/* Upsample by a factor 2, high quality */\nvoid SKP_Silk_resampler_private_up2_HQ_wrapper(\n\tvoid\t                        *SS,\t\t    /* I/O: Resampler state (unused)\t\t\t\t*/\n    SKP_int16                       *out,           /* O:   Output signal [ 2 * len ]               */\n    const SKP_int16                 *in,            /* I:   Input signal [ len ]                    */\n    SKP_int32                       len             /* I:   Number of input samples                 */\n);\n\n/* Upsample by a factor 2, high quality */\nvoid SKP_Silk_resampler_private_up2_HQ(\n\tSKP_int32\t                    *S,\t\t\t    /* I/O: Resampler state [ 6 ]\t\t\t\t\t*/\n    SKP_int16                       *out,           /* O:   Output signal [ 2 * len ]               */\n    const SKP_int16                 *in,            /* I:   Input signal [ len ]                    */\n    SKP_int32                       len             /* I:   Number of input samples                 */\n);\n\n/* Upsample 4x, low quality */\nvoid SKP_Silk_resampler_private_up4(\n    SKP_int32                       *S,             /* I/O: State vector [ 2 ]                      */\n    SKP_int16                       *out,           /* O:   Output signal [ 4 * len ]               */\n    const SKP_int16                 *in,            /* I:   Input signal [ len ]                    */\n    SKP_int32                       len             /* I:   Number of input samples                 */\n);\n\n/* Downsample 4x, low quality */\nvoid SKP_Silk_resampler_private_down4(\n    SKP_int32                       *S,             /* I/O: State vector [ 2 ]                      */\n    SKP_int16                       *out,           /* O:   Output signal [ floor(len/2) ]          */\n    const SKP_int16                 *in,            /* I:   Input signal [ len ]                    */\n    SKP_int32                       inLen           /* I:   Number of input samples                 */\n);\n\n/* Second order AR filter */\nvoid SKP_Silk_resampler_private_AR2(\n\tSKP_int32\t\t\t\t\t    S[],\t\t    /* I/O: State vector [ 2 ]\t\t\t    \t    */\n\tSKP_int32\t\t\t\t\t    out_Q8[],\t\t/* O:\tOutput signal\t\t\t\t    \t    */\n\tconst SKP_int16\t\t\t\t    in[],\t\t\t/* I:\tInput signal\t\t\t\t    \t    */\n\tconst SKP_int16\t\t\t\t    A_Q14[],\t\t/* I:\tAR coefficients, Q14 \t                */\n\tSKP_int32\t\t\t\t        len\t\t\t\t/* I:\tSignal length\t\t\t\t        \t*/\n);\n\n/* Fourth order ARMA filter */\nvoid SKP_Silk_resampler_private_ARMA4(\n\tSKP_int32\t\t\t\t\t    S[],\t\t    /* I/O: State vector [ 4 ]\t\t\t    \t    */\n\tSKP_int16\t\t\t\t\t    out[],\t\t    /* O:\tOutput signal\t\t\t\t    \t    */\n\tconst SKP_int16\t\t\t\t    in[],\t\t\t/* I:\tInput signal\t\t\t\t    \t    */\n\tconst SKP_int16\t\t\t\t    Coef[],\t\t    /* I:\tARMA coefficients [ 7 ]                 */\n\tSKP_int32\t\t\t\t        len\t\t\t\t/* I:\tSignal length\t\t\t\t        \t*/\n);\n\n\n#ifdef __cplusplus\n}\n#endif\n#endif // SKP_Silk_RESAMPLER_H\n\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_resampler_rom.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*                                                                      *\n * File Name:    SKP_Silk_resample_rom.h                              *\n *                                                                      *\n * Description: Header file for FIR resampling of                       *\n *                32 and 44 kHz input                                   *\n *                                                                      *\n * Copyright 2007 (c), Skype Limited                                    *\n * All rights reserved.                                                 *\n *                                                                      *\n * Date: 070807                                                         *\n *                                                                      */\n\n#ifndef _SKP_SILK_FIX_RESAMPLER_ROM_H_\n#define _SKP_SILK_FIX_RESAMPLER_ROM_H_\n\n#ifdef  __cplusplus\nextern \"C\"\n{\n#endif\n\n#include \"SKP_Silk_typedef.h\"\n#include \"SKP_Silk_resampler_structs.h\"\n\n#define RESAMPLER_DOWN_ORDER_FIR                12\n#define RESAMPLER_ORDER_FIR_144                 6\n\n\n/* Tables for 2x downsampler. Values above 32767 intentionally wrap to a negative value. */\nextern const SKP_int16 SKP_Silk_resampler_down2_0;\nextern const SKP_int16 SKP_Silk_resampler_down2_1;\n\n/* Tables for 2x upsampler, low quality. Values above 32767 intentionally wrap to a negative value. */\nextern const SKP_int16 SKP_Silk_resampler_up2_lq_0;\nextern const SKP_int16 SKP_Silk_resampler_up2_lq_1;\n\n/* Tables for 2x upsampler, high quality. Values above 32767 intentionally wrap to a negative value. */\nextern const SKP_int16 SKP_Silk_resampler_up2_hq_0[ 2 ];\nextern const SKP_int16 SKP_Silk_resampler_up2_hq_1[ 2 ];\nextern const SKP_int16 SKP_Silk_resampler_up2_hq_notch[ 4 ];\n\n/* Tables with IIR and FIR coefficients for fractional downsamplers */\nextern const SKP_int16 SKP_Silk_Resampler_3_4_COEFS[ 2 + 3 * RESAMPLER_DOWN_ORDER_FIR / 2 ];\nextern const SKP_int16 SKP_Silk_Resampler_2_3_COEFS[ 2 + 2 * RESAMPLER_DOWN_ORDER_FIR / 2 ];\nextern const SKP_int16 SKP_Silk_Resampler_1_2_COEFS[ 2 +     RESAMPLER_DOWN_ORDER_FIR / 2 ];\nextern const SKP_int16 SKP_Silk_Resampler_3_8_COEFS[ 2 + 3 * RESAMPLER_DOWN_ORDER_FIR / 2 ];\nextern const SKP_int16 SKP_Silk_Resampler_1_3_COEFS[ 2 +     RESAMPLER_DOWN_ORDER_FIR / 2 ];\nextern const SKP_int16 SKP_Silk_Resampler_2_3_COEFS_LQ[ 2 + 2 * 2 ];\nextern const SKP_int16 SKP_Silk_Resampler_1_3_COEFS_LQ[ 2 + 3 ];\n\n/* Tables with coefficients for 4th order ARMA filter */\nextern const SKP_int16 SKP_Silk_Resampler_320_441_ARMA4_COEFS[ 7 ];\nextern const SKP_int16 SKP_Silk_Resampler_240_441_ARMA4_COEFS[ 7 ];\nextern const SKP_int16 SKP_Silk_Resampler_160_441_ARMA4_COEFS[ 7 ];\nextern const SKP_int16 SKP_Silk_Resampler_120_441_ARMA4_COEFS[ 7 ];\nextern const SKP_int16 SKP_Silk_Resampler_80_441_ARMA4_COEFS[ 7 ];\n\n/* Table with interplation fractions of 1/288 : 2/288 : 287/288 (432 Words) */\nextern const SKP_int16 SKP_Silk_resampler_frac_FIR_144[ 144 ][ RESAMPLER_ORDER_FIR_144 / 2 ];\n\n#ifdef  __cplusplus\n}\n#endif\n\n#endif // _SKP_SILK_FIX_RESAMPLER_ROM_H_\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_resampler_structs.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n/*\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * File Name:\tSKP_Silk_resampler_structs.h\t\t\t\t\t\t\t*\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n * Description: Structs for IIR/FIR resamplers\t\t\t\t\t\t\t*\n *                                                                      *\n * Copyright 2010 (c), Skype Limited                                    *\n * All rights reserved.\t\t\t\t\t\t\t\t\t\t\t\t\t*\n *\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t*\n *                                                                      */\n\n#ifndef SKP_Silk_RESAMPLER_STRUCTS_H\n#define SKP_Silk_RESAMPLER_STRUCTS_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* Flag to enable support for input/output sampling rates above 48 kHz. Turn off for embedded devices */\n#define RESAMPLER_SUPPORT_ABOVE_48KHZ                   1\n\n#define SKP_Silk_RESAMPLER_MAX_FIR_ORDER                 16\n#define SKP_Silk_RESAMPLER_MAX_IIR_ORDER                 6\n\n\ntypedef struct _SKP_Silk_resampler_state_struct{\n\tSKP_int32       sIIR[ SKP_Silk_RESAMPLER_MAX_IIR_ORDER ];        /* this must be the first element of this struct */\n\tSKP_int32       sFIR[ SKP_Silk_RESAMPLER_MAX_FIR_ORDER ];\n\tSKP_int32       sDown2[ 2 ];\n\tvoid            (*resampler_function)( void *, SKP_int16 *, const SKP_int16 *, SKP_int32 );\n\tvoid            (*up2_function)(  SKP_int32 *, SKP_int16 *, const SKP_int16 *, SKP_int32 );\n    SKP_int32       batchSize;\n\tSKP_int32       invRatio_Q16;\n\tSKP_int32       FIR_Fracs;\n    SKP_int32       input2x;\n\tconst SKP_int16\t*Coefs;\n#if RESAMPLER_SUPPORT_ABOVE_48KHZ\n\tSKP_int32       sDownPre[ 2 ];\n\tSKP_int32       sUpPost[ 2 ];\n\tvoid            (*down_pre_function)( SKP_int32 *, SKP_int16 *, const SKP_int16 *, SKP_int32 );\n\tvoid            (*up_post_function)(  SKP_int32 *, SKP_int16 *, const SKP_int16 *, SKP_int32 );\n\tSKP_int32       batchSizePrePost;\n\tSKP_int32       ratio_Q16;\n\tSKP_int32       nPreDownsamplers;\n\tSKP_int32       nPostUpsamplers;\n#endif\n\tSKP_int32 magic_number;\n} SKP_Silk_resampler_state_struct;\n\n#ifdef __cplusplus\n}\n#endif\n#endif /* SKP_Silk_RESAMPLER_STRUCTS_H */\n\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_setup_complexity.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#include \"SKP_Silk_main.h\"\n#include \"SKP_Silk_tuning_parameters.h\"\n\nSKP_INLINE SKP_int SKP_Silk_setup_complexity(\n    SKP_Silk_encoder_state          *psEncC,            /* I/O  Pointer to Silk encoder state           */\n    SKP_int                         Complexity          /* I    Complexity (0->low; 1->medium; 2->high) */\n)\n{\n    SKP_int ret = SKP_SILK_NO_ERROR;\n\n    /* Check that settings are valid */\n    if( LOW_COMPLEXITY_ONLY && Complexity != 0 ) { \n        ret = SKP_SILK_ENC_INVALID_COMPLEXITY_SETTING;\n    }\n\n    /* Set encoding complexity */\n    if( Complexity == 0 || LOW_COMPLEXITY_ONLY ) {\n        /* Low complexity */\n        psEncC->Complexity                      = 0;\n        psEncC->pitchEstimationComplexity       = PITCH_EST_COMPLEXITY_LC_MODE;\n        psEncC->pitchEstimationThreshold_Q16    = SKP_FIX_CONST( FIND_PITCH_CORRELATION_THRESHOLD_LC_MODE, 16 );\n        psEncC->pitchEstimationLPCOrder         = 6;\n        psEncC->shapingLPCOrder                 = 8;\n        psEncC->la_shape                        = 3 * psEncC->fs_kHz;\n        psEncC->nStatesDelayedDecision          = 1;\n        psEncC->useInterpolatedNLSFs            = 0;\n        psEncC->LTPQuantLowComplexity           = 1;\n        psEncC->NLSF_MSVQ_Survivors             = MAX_NLSF_MSVQ_SURVIVORS_LC_MODE;\n        psEncC->warping_Q16                     = 0;\n    } else if( Complexity == 1 ) {\n        /* Medium complexity */\n        psEncC->Complexity                      = 1;\n        psEncC->pitchEstimationComplexity       = PITCH_EST_COMPLEXITY_MC_MODE;\n        psEncC->pitchEstimationThreshold_Q16    = SKP_FIX_CONST( FIND_PITCH_CORRELATION_THRESHOLD_MC_MODE, 16 );\n        psEncC->pitchEstimationLPCOrder         = 12;\n        psEncC->shapingLPCOrder                 = 12;\n        psEncC->la_shape                        = 5 * psEncC->fs_kHz;\n        psEncC->nStatesDelayedDecision          = 2;\n        psEncC->useInterpolatedNLSFs            = 0;\n        psEncC->LTPQuantLowComplexity           = 0;\n        psEncC->NLSF_MSVQ_Survivors             = MAX_NLSF_MSVQ_SURVIVORS_MC_MODE;\n        psEncC->warping_Q16                     = psEncC->fs_kHz * SKP_FIX_CONST( WARPING_MULTIPLIER, 16 );\n    } else if( Complexity == 2 ) {\n        /* High complexity */\n        psEncC->Complexity                      = 2;\n        psEncC->pitchEstimationComplexity       = PITCH_EST_COMPLEXITY_HC_MODE;\n        psEncC->pitchEstimationThreshold_Q16    = SKP_FIX_CONST( FIND_PITCH_CORRELATION_THRESHOLD_HC_MODE, 16 );\n        psEncC->pitchEstimationLPCOrder         = 16;\n        psEncC->shapingLPCOrder                 = 16;\n        psEncC->la_shape                        = 5 * psEncC->fs_kHz;\n        psEncC->nStatesDelayedDecision          = MAX_DEL_DEC_STATES;\n        psEncC->useInterpolatedNLSFs            = 1;\n        psEncC->LTPQuantLowComplexity           = 0;\n        psEncC->NLSF_MSVQ_Survivors             = MAX_NLSF_MSVQ_SURVIVORS;\n        psEncC->warping_Q16                     = psEncC->fs_kHz * SKP_FIX_CONST( WARPING_MULTIPLIER, 16 );\n    } else {\n        ret = SKP_SILK_ENC_INVALID_COMPLEXITY_SETTING;\n    }\n\n    /* Do not allow higher pitch estimation LPC order than predict LPC order */\n    psEncC->pitchEstimationLPCOrder             = SKP_min_int( psEncC->pitchEstimationLPCOrder, psEncC->predictLPCOrder );\n    psEncC->shapeWinLength                      = 5 * psEncC->fs_kHz + 2 * psEncC->la_shape;\n\n    SKP_assert( psEncC->pitchEstimationLPCOrder <= MAX_FIND_PITCH_LPC_ORDER );\n    SKP_assert( psEncC->shapingLPCOrder         <= MAX_SHAPE_LPC_ORDER      );\n    SKP_assert( psEncC->nStatesDelayedDecision  <= MAX_DEL_DEC_STATES       );\n    SKP_assert( psEncC->warping_Q16             <= 32767                    );\n    SKP_assert( psEncC->la_shape                <= LA_SHAPE_MAX             );\n    SKP_assert( psEncC->shapeWinLength          <= SHAPE_LPC_WIN_MAX        );\n\n    return( ret );\n}\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_structs.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_STRUCTS_H\n#define SKP_SILK_STRUCTS_H\n\n#include \"SKP_Silk_typedef.h\"\n#include \"SKP_Silk_SigProc_FIX.h\"\n#include \"SKP_Silk_define.h\"\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n\n/************************************/\n/* Noise shaping quantization state */\n/************************************/\ntypedef struct {\n    SKP_int16   xq[           2 * MAX_FRAME_LENGTH ]; /* Buffer for quantized output signal */\n    SKP_int32   sLTP_shp_Q10[ 2 * MAX_FRAME_LENGTH ];\n    SKP_int32   sLPC_Q14[ MAX_FRAME_LENGTH / NB_SUBFR + NSQ_LPC_BUF_LENGTH ];\n    SKP_int32   sAR2_Q14[ MAX_SHAPE_LPC_ORDER ];\n    SKP_int32   sLF_AR_shp_Q12;\n    SKP_int     lagPrev;\n    SKP_int     sLTP_buf_idx;\n    SKP_int     sLTP_shp_buf_idx;\n    SKP_int32   rand_seed;\n    SKP_int32   prev_inv_gain_Q16;\n    SKP_int     rewhite_flag;\n} SKP_Silk_nsq_state; /* FIX*/\n\n/* Struct for Low BitRate Redundant (LBRR) information */\ntypedef struct {\n    SKP_uint8   payload[ MAX_ARITHM_BYTES ];    \n    SKP_int     nBytes;                         /* Number of bytes in payload                               */\n    SKP_int     usage;                          /* Tells how the payload should be used as FEC              */\n} SKP_SILK_LBRR_struct;\n\n/********************************/\n/* VAD state                    */\n/********************************/\ntypedef struct {\n    SKP_int32   AnaState[ 2 ];                  /* Analysis filterbank state: 0-8 kHz                       */\n    SKP_int32   AnaState1[ 2 ];                 /* Analysis filterbank state: 0-4 kHz                       */\n    SKP_int32   AnaState2[ 2 ];                 /* Analysis filterbank state: 0-2 kHz                       */\n    SKP_int32   XnrgSubfr[ VAD_N_BANDS ];       /* Subframe energies                                        */\n    SKP_int32   NrgRatioSmth_Q8[ VAD_N_BANDS ]; /* Smoothed energy level in each band                       */\n    SKP_int16   HPstate;                        /* State of differentiator in the lowest band               */\n    SKP_int32   NL[ VAD_N_BANDS ];              /* Noise energy level in each band                          */\n    SKP_int32   inv_NL[ VAD_N_BANDS ];          /* Inverse noise energy level in each band                  */\n    SKP_int32   NoiseLevelBias[ VAD_N_BANDS ];  /* Noise level estimator bias/offset                        */\n    SKP_int32   counter;                        /* Frame counter used in the initial phase                  */\n} SKP_Silk_VAD_state;\n\n/*******************************/\n/* Range encoder/decoder state */\n/*******************************/\ntypedef struct {\n    SKP_int32   bufferLength;\n    SKP_int32   bufferIx;\n    SKP_uint32  base_Q32;\n    SKP_uint32  range_Q16;\n    SKP_int32   error;\n    SKP_uint8   buffer[ MAX_ARITHM_BYTES ];     /* Buffer containing payload                                */\n} SKP_Silk_range_coder_state;\n\n/* Input frequency range detection struct */\ntypedef struct {\n    SKP_int32                   S_HP_8_kHz[ NB_SOS ][ 2 ];  /* HP filter State */\n    SKP_int32                   ConsecSmplsAboveThres;\n    SKP_int32                   ActiveSpeech_ms;            /* Accumulated time with active speech */\n    SKP_int                     SWB_detected;               /* Flag to indicate SWB input */\n    SKP_int                     WB_detected;                /* Flag to indicate WB input */\n} SKP_Silk_detect_SWB_state;\n\n#if SWITCH_TRANSITION_FILTERING\n/* Variable cut-off low-pass filter state */\ntypedef struct {\n    SKP_int32                   In_LP_State[ 2 ];           /* Low pass filter state */\n    SKP_int32                   transition_frame_no;        /* Counter which is mapped to a cut-off frequency */\n    SKP_int                     mode;                       /* Operating mode, 0: switch down, 1: switch up */\n} SKP_Silk_LP_state;\n#endif\n\n/* Structure for one stage of MSVQ */\ntypedef struct {\n    const SKP_int32             nVectors;\n    const SKP_int16             *CB_NLSF_Q15;\n    const SKP_int16             *Rates_Q5;\n} SKP_Silk_NLSF_CBS;\n\n/* Structure containing NLSF MSVQ codebook */\ntypedef struct {\n    const SKP_int32             nStages;\n\n    /* Fields for (de)quantizing */\n    const SKP_Silk_NLSF_CBS     *CBStages;\n    const SKP_int               *NDeltaMin_Q15;\n\n    /* Fields for arithmetic (de)coding */\n    const SKP_uint16            *CDF;\n    const SKP_uint16 * const    *StartPtr;\n    const SKP_int               *MiddleIx;\n} SKP_Silk_NLSF_CB_struct;\n\n/********************************/\n/* Encoder state                */\n/********************************/\ntypedef struct {\n    SKP_Silk_range_coder_state      sRC;                            /* Range coder state                                                    */\n    SKP_Silk_range_coder_state      sRC_LBRR;                       /* Range coder state (for low bitrate redundancy)                       */\n    SKP_Silk_nsq_state              sNSQ;                           /* Noise Shape Quantizer State                                          */\n    SKP_Silk_nsq_state              sNSQ_LBRR;                      /* Noise Shape Quantizer State ( for low bitrate redundancy )           */\n\n#if HIGH_PASS_INPUT\n    SKP_int32                       In_HP_State[ 2 ];               /* High pass filter state                                               */\n#endif\n#if SWITCH_TRANSITION_FILTERING\n    SKP_Silk_LP_state               sLP;                            /* Low pass filter state */\n#endif\n    SKP_Silk_VAD_state              sVAD;                           /* Voice activity detector state                                        */\n\n    SKP_int                         LBRRprevLastGainIndex;\n    SKP_int                         prev_sigtype;\n    SKP_int                         typeOffsetPrev;                 /* Previous signal type and quantization offset                         */\n    SKP_int                         prevLag;\n    SKP_int                         prev_lagIndex;\n    SKP_int32                       API_fs_Hz;                      /* API sampling frequency (Hz)                                          */\n    SKP_int32                       prev_API_fs_Hz;                 /* Previous API sampling frequency (Hz)                                 */\n    SKP_int                         maxInternal_fs_kHz;             /* Maximum internal sampling frequency (kHz)                            */\n    SKP_int                         fs_kHz;                         /* Internal sampling frequency (kHz)                                    */\n    SKP_int                         fs_kHz_changed;                 /* Did we switch yet?                                                   */\n    SKP_int                         frame_length;                   /* Frame length (samples)                                               */\n    SKP_int                         subfr_length;                   /* Subframe length (samples)                                            */\n    SKP_int                         la_pitch;                       /* Look-ahead for pitch analysis (samples)                              */\n    SKP_int                         la_shape;                       /* Look-ahead for noise shape analysis (samples)                        */\n    SKP_int                         shapeWinLength;                 /* Window length for noise shape analysis (samples)                     */\n    SKP_int32                       TargetRate_bps;                 /* Target bitrate (bps)                                                 */\n    SKP_int                         PacketSize_ms;                  /* Number of milliseconds to put in each packet                         */\n    SKP_int                         PacketLoss_perc;                /* Packet loss rate measured by farend                                  */\n    SKP_int32                       frameCounter;\n    SKP_int                         Complexity;                     /* Complexity setting: 0-> low; 1-> medium; 2->high                     */\n    SKP_int                         nStatesDelayedDecision;         /* Number of states in delayed decision quantization                    */\n    SKP_int                         useInterpolatedNLSFs;           /* Flag for using NLSF interpolation                                    */\n    SKP_int                         shapingLPCOrder;                /* Filter order for noise shaping filters                               */\n    SKP_int                         predictLPCOrder;                /* Filter order for prediction filters                                  */\n    SKP_int                         pitchEstimationComplexity;      /* Complexity level for pitch estimator                                 */\n    SKP_int                         pitchEstimationLPCOrder;        /* Whitening filter order for pitch estimator                           */\n    SKP_int32                       pitchEstimationThreshold_Q16;   /* Threshold for pitch estimator                                        */\n    SKP_int                         LTPQuantLowComplexity;          /* Flag for low complexity LTP quantization                             */\n    SKP_int                         NLSF_MSVQ_Survivors;            /* Number of survivors in NLSF MSVQ                                     */\n    SKP_int                         first_frame_after_reset;        /* Flag for deactivating NLSF interp. and fluc. reduction after resets  */\n    SKP_int                         controlled_since_last_payload;  /* Flag for ensuring codec_control only runs once per packet            */\n\tSKP_int                         warping_Q16;                    /* Warping parameter for warped noise shaping                           */\n\n    /* Input/output buffering */\n    SKP_int16                       inputBuf[ MAX_FRAME_LENGTH ];   /* buffer containin input signal                                        */\n    SKP_int                         inputBufIx;\n    SKP_int                         nFramesInPayloadBuf;            /* number of frames sitting in outputBuf                                */\n    SKP_int                         nBytesInPayloadBuf;             /* number of bytes sitting in outputBuf                                 */\n\n    /* Parameters For LTP scaling Control */\n    SKP_int                         frames_since_onset;\n\n    const SKP_Silk_NLSF_CB_struct   *psNLSF_CB[ 2 ];                /* Pointers to voiced/unvoiced NLSF codebooks */\n\n    /* Struct for Inband LBRR */ \n    SKP_SILK_LBRR_struct            LBRR_buffer[ MAX_LBRR_DELAY ];\n    SKP_int                         oldest_LBRR_idx;\n    SKP_int                         useInBandFEC;                   /* Saves the API setting for query                                      */\n    SKP_int                         LBRR_enabled;\n    SKP_int                         LBRR_GainIncreases;             /* Number of shifts to Gains to get LBRR rate Voiced frames             */\n\n    /* Bitrate control */\n    SKP_int32                       bitrateDiff;                    /* Accumulated diff. between the target bitrate and the switch bitrates */\n    SKP_int32                       bitrate_threshold_up;           /* Threshold for switching to a higher internal sample frequency        */\n    SKP_int32                       bitrate_threshold_down;         /* Threshold for switching to a lower internal sample frequency         */\n\n    SKP_Silk_resampler_state_struct  resampler_state;\n\n    /* DTX */\n    SKP_int                         noSpeechCounter;                /* Counts concecutive nonactive frames, used by DTX                     */\n    SKP_int                         useDTX;                         /* Flag to enable DTX                                                   */\n    SKP_int                         inDTX;                          /* Flag to signal DTX period                                            */\n    SKP_int                         vadFlag;                        /* Flag to indicate Voice Activity                                      */\n\n    /* Struct for detecting SWB input */\n    SKP_Silk_detect_SWB_state       sSWBdetect;\n\n\n    /* Buffers */\n    SKP_int8                        q[ MAX_FRAME_LENGTH ];      /* pulse signal buffer */\n    SKP_int8                        q_LBRR[ MAX_FRAME_LENGTH ]; /* pulse signal buffer */\n\n} SKP_Silk_encoder_state;\n\n\n/************************/\n/* Encoder control      */\n/************************/\ntypedef struct {\n    /* Quantization indices */\n    SKP_int     lagIndex;\n    SKP_int     contourIndex;\n    SKP_int     PERIndex;\n    SKP_int     LTPIndex[ NB_SUBFR ];\n    SKP_int     NLSFIndices[ NLSF_MSVQ_MAX_CB_STAGES ];  /* NLSF path of quantized LSF vector   */\n    SKP_int     NLSFInterpCoef_Q2;\n    SKP_int     GainsIndices[ NB_SUBFR ];\n    SKP_int32   Seed;\n    SKP_int     LTP_scaleIndex;\n    SKP_int     RateLevelIndex;\n    SKP_int     QuantOffsetType;\n    SKP_int     sigtype;\n\n    /* Prediction and coding parameters */\n    SKP_int     pitchL[ NB_SUBFR ];\n\n    SKP_int     LBRR_usage;                     /* Low bitrate redundancy usage                             */\n} SKP_Silk_encoder_control;\n\n/* Struct for Packet Loss Concealment */\ntypedef struct {\n    SKP_int32   pitchL_Q8;                      /* Pitch lag to use for voiced concealment                  */\n    SKP_int16   LTPCoef_Q14[ LTP_ORDER ];       /* LTP coeficients to use for voiced concealment            */\n    SKP_int16   prevLPC_Q12[ MAX_LPC_ORDER ];\n    SKP_int     last_frame_lost;                /* Was previous frame lost                                  */\n    SKP_int32   rand_seed;                      /* Seed for unvoiced signal generation                      */\n    SKP_int16   randScale_Q14;                  /* Scaling of unvoiced random signal                        */\n    SKP_int32   conc_energy;\n    SKP_int     conc_energy_shift;\n    SKP_int16   prevLTP_scale_Q14;\n    SKP_int32   prevGain_Q16[ NB_SUBFR ];\n    SKP_int     fs_kHz;\n} SKP_Silk_PLC_struct;\n\n/* Struct for CNG */\ntypedef struct {\n    SKP_int32   CNG_exc_buf_Q10[ MAX_FRAME_LENGTH ];\n    SKP_int     CNG_smth_NLSF_Q15[ MAX_LPC_ORDER ];\n    SKP_int32   CNG_synth_state[ MAX_LPC_ORDER ];\n    SKP_int32   CNG_smth_Gain_Q16;\n    SKP_int32   rand_seed;\n    SKP_int     fs_kHz;\n} SKP_Silk_CNG_struct;\n\n/********************************/\n/* Decoder state                */\n/********************************/\ntypedef struct {\n    SKP_Silk_range_coder_state  sRC;                            /* Range coder state                                                    */\n    SKP_int32       prev_inv_gain_Q16;\n    SKP_int32       sLTP_Q16[ 2 * MAX_FRAME_LENGTH ];\n    SKP_int32       sLPC_Q14[ MAX_FRAME_LENGTH / NB_SUBFR + MAX_LPC_ORDER ];\n    SKP_int32       exc_Q10[ MAX_FRAME_LENGTH ];\n    SKP_int32       res_Q10[ MAX_FRAME_LENGTH ];\n    SKP_int16       outBuf[ 2 * MAX_FRAME_LENGTH ];             /* Buffer for output signal                                             */\n    SKP_int         lagPrev;                                    /* Previous Lag                                                         */\n    SKP_int         LastGainIndex;                              /* Previous gain index                                                  */\n    SKP_int         LastGainIndex_EnhLayer;                     /* Previous gain index                                                  */\n    SKP_int         typeOffsetPrev;                             /* Previous signal type and quantization offset                         */\n    SKP_int32       HPState[ DEC_HP_ORDER ];                    /* HP filter state                                                      */\n    const SKP_int16 *HP_A;                                      /* HP filter AR coefficients                                            */\n    const SKP_int16 *HP_B;                                      /* HP filter MA coefficients                                            */\n    SKP_int         fs_kHz;                                     /* Sampling frequency in kHz                                            */\n    SKP_int32       prev_API_sampleRate;                        /* Previous API sample frequency (Hz)                                   */\n    SKP_int         frame_length;                               /* Frame length (samples)                                               */\n    SKP_int         subfr_length;                               /* Subframe length (samples)                                            */\n    SKP_int         LPC_order;                                  /* LPC order                                                            */\n    SKP_int         prevNLSF_Q15[ MAX_LPC_ORDER ];              /* Used to interpolate LSFs                                             */\n    SKP_int         first_frame_after_reset;                    /* Flag for deactivating NLSF interp. and fluc. reduction after resets  */\n\n    /* For buffering payload in case of more frames per packet */\n    SKP_int         nBytesLeft;\n    SKP_int         nFramesDecoded;\n    SKP_int         nFramesInPacket;\n    SKP_int         moreInternalDecoderFrames;\n    SKP_int         FrameTermination;\n\n    SKP_Silk_resampler_state_struct  resampler_state;\n\n    const SKP_Silk_NLSF_CB_struct *psNLSF_CB[ 2 ];      /* Pointers to voiced/unvoiced NLSF codebooks */\n\n    /* Parameters used to investigate if inband FEC is used */\n    SKP_int         vadFlag;\n    SKP_int         no_FEC_counter;                             /* Counts number of frames wo inband FEC                                */\n    SKP_int         inband_FEC_offset;                          /* 0: no FEC, 1: FEC with 1 packet offset, 2: FEC w 2 packets offset    */ \n\n    /* CNG state */\n    SKP_Silk_CNG_struct sCNG;\n\n    /* Stuff used for PLC */\n    SKP_int         lossCnt;\n    SKP_int         prev_sigtype;                               /* Previous sigtype                                                     */\n\n    SKP_Silk_PLC_struct sPLC;\n\n\n\n} SKP_Silk_decoder_state;\n\n/************************/\n/* Decoder control      */\n/************************/\ntypedef struct {\n    /* prediction and coding parameters */\n    SKP_int             pitchL[ NB_SUBFR ];\n    SKP_int32           Gains_Q16[ NB_SUBFR ];\n    SKP_int32           Seed;\n    /* holds interpolated and final coefficients, 4-byte aligned */\n    SKP_DWORD_ALIGN SKP_int16 PredCoef_Q12[ 2 ][ MAX_LPC_ORDER ];\n    SKP_int16           LTPCoef_Q14[ LTP_ORDER * NB_SUBFR ];\n    SKP_int             LTP_scale_Q14;\n\n    /* quantization indices */\n    SKP_int             PERIndex;\n    SKP_int             RateLevelIndex;\n    SKP_int             QuantOffsetType;\n    SKP_int             sigtype;\n    SKP_int             NLSFInterpCoef_Q2;\n} SKP_Silk_decoder_control;\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_structs_FIX.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_STRUCTS_FIX_H\n#define SKP_SILK_STRUCTS_FIX_H\n\n#include \"SKP_Silk_typedef.h\"\n#include \"SKP_Silk_main.h\"\n#include \"SKP_Silk_structs.h\"\n\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n/********************************/\n/* Noise shaping analysis state */\n/********************************/\ntypedef struct {\n    SKP_int     LastGainIndex;\n    SKP_int32   HarmBoost_smth_Q16;\n    SKP_int32   HarmShapeGain_smth_Q16;\n    SKP_int32   Tilt_smth_Q16;\n} SKP_Silk_shape_state_FIX;\n\n/********************************/\n/* Prefilter state              */\n/********************************/\ntypedef struct {\n    SKP_int16   sLTP_shp[ LTP_BUF_LENGTH ];\n    SKP_int32   sAR_shp[ MAX_SHAPE_LPC_ORDER + 1 ]; // Q14\n    SKP_int     sLTP_shp_buf_idx;\n    SKP_int32   sLF_AR_shp_Q12;\n    SKP_int32   sLF_MA_shp_Q12;\n    SKP_int     sHarmHP;\n    SKP_int32   rand_seed;\n    SKP_int     lagPrev;\n} SKP_Silk_prefilter_state_FIX;\n\n/*****************************/\n/* Prediction analysis state */\n/*****************************/\ntypedef struct {\n    SKP_int   pitch_LPC_win_length;\n    SKP_int   min_pitch_lag;                                        /* Lowest possible pitch lag (samples)  */\n    SKP_int   max_pitch_lag;                                        /* Highest possible pitch lag (samples) */\n    SKP_int   prev_NLSFq_Q15[ MAX_LPC_ORDER ];                      /* Previously quantized NLSF vector     */\n} SKP_Silk_predict_state_FIX;\n\n\n/********************************/\n/* Encoder state FIX            */\n/********************************/\ntypedef struct {\n    SKP_Silk_encoder_state          sCmn;                           /* Common struct, shared with floating-point code */\n\n#if HIGH_PASS_INPUT\n    SKP_int32                       variable_HP_smth1_Q15;          /* State of first smoother                                              */\n    SKP_int32                       variable_HP_smth2_Q15;          /* State of second smoother                                             */\n#endif\n    SKP_Silk_shape_state_FIX        sShape;                         /* Shape state                                                          */\n    SKP_Silk_prefilter_state_FIX    sPrefilt;                       /* Prefilter State                                                      */\n    SKP_Silk_predict_state_FIX      sPred;                          /* Prediction state                                                     */\n\n    /* Buffer for find pitch and noise shape analysis */\n    SKP_DWORD_ALIGN SKP_int16 x_buf[ 2 * MAX_FRAME_LENGTH + LA_SHAPE_MAX ];\n    SKP_int                         LTPCorr_Q15;                    /* Normalized correlation from pitch lag estimator, approx Q15          */\n    SKP_int                         mu_LTP_Q8;                      /* Rate-distortion tradeoff in LTP quantization                         */\n    SKP_int32                       SNR_dB_Q7;                      /* Quality setting                                                      */\n    SKP_int32                       avgGain_Q16;                    /* average gain during active speech                                    */\n    SKP_int32                       avgGain_Q16_one_bit_per_sample; /* average gain during active speech                                    */\n    SKP_int                         BufferedInChannel_ms;           /* Simulated number of ms buffer because of exceeded TargetRate_bps     */\n    SKP_int                         speech_activity_Q8;             /* Speech activity in Q8                                                */\n\n    /* Parameters For LTP scaling Control */\n    SKP_int                         prevLTPredCodGain_Q7;\n    SKP_int                         HPLTPredCodGain_Q7;\n\n    SKP_int32                       inBandFEC_SNR_comp_Q8;          /* Compensation to SNR_dB when using inband FEC Voiced      */\n\n} SKP_Silk_encoder_state_FIX;\n\n/************************/\n/* Encoder control FIX  */\n/************************/\ntypedef struct {\n    SKP_Silk_encoder_control        sCmn;                           /* Common struct, shared with floating-point code */\n\n    /* Prediction and coding parameters */\n    SKP_int32                   Gains_Q16[ NB_SUBFR ];\n    SKP_DWORD_ALIGN SKP_int16   PredCoef_Q12[ 2 ][ MAX_LPC_ORDER ];\n    SKP_int16                   LTPCoef_Q14[ LTP_ORDER * NB_SUBFR ];\n    SKP_int                     LTP_scale_Q14;\n\n    /* Noise shaping parameters */\n    /* Testing */\n    SKP_DWORD_ALIGN SKP_int16 AR1_Q13[ NB_SUBFR * MAX_SHAPE_LPC_ORDER ];\n    SKP_DWORD_ALIGN SKP_int16 AR2_Q13[ NB_SUBFR * MAX_SHAPE_LPC_ORDER ];\n    SKP_int32   LF_shp_Q14[        NB_SUBFR ];          /* Packs two int16 coefficients per int32 value             */\n    SKP_int     GainsPre_Q14[      NB_SUBFR ];\n    SKP_int     HarmBoost_Q14[     NB_SUBFR ];\n    SKP_int     Tilt_Q14[          NB_SUBFR ];\n    SKP_int     HarmShapeGain_Q14[ NB_SUBFR ];\n    SKP_int     Lambda_Q10;\n    SKP_int     input_quality_Q14;\n    SKP_int     coding_quality_Q14;\n    SKP_int32   pitch_freq_low_Hz;\n    SKP_int     current_SNR_dB_Q7;\n\n    /* measures */\n    SKP_int     sparseness_Q8;\n    SKP_int32   predGain_Q16;\n    SKP_int     LTPredCodGain_Q7;\n    SKP_int     input_quality_bands_Q15[ VAD_N_BANDS ];\n    SKP_int     input_tilt_Q15;\n    SKP_int32   ResNrg[ NB_SUBFR ];             /* Residual energy per subframe                             */\n    SKP_int     ResNrgQ[ NB_SUBFR ];            /* Q domain for the residual energy > 0                     */\n    \n} SKP_Silk_encoder_control_FIX;\n\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_tables.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_TABLES_H\n#define SKP_SILK_TABLES_H\n\n#include \"SKP_Silk_define.h\"\n#include \"SKP_Silk_structs.h\"\n\n#define PITCH_EST_MAX_LAG_MS                18          /* 18 ms -> 56 Hz */\n#define PITCH_EST_MIN_LAG_MS                2           /* 2 ms -> 500 Hz */\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n/* entropy coding tables */\nextern const SKP_uint16 SKP_Silk_type_offset_CDF[ 5 ];                                              /*   5 */\nextern const SKP_uint16 SKP_Silk_type_offset_joint_CDF[ 4 ][ 5 ];                                   /*  20 */\nextern const SKP_int    SKP_Silk_type_offset_CDF_offset;\n\nextern const SKP_uint16 SKP_Silk_gain_CDF[ 2 ][ N_LEVELS_QGAIN + 1 ];                               /* 130 */\nextern const SKP_int    SKP_Silk_gain_CDF_offset;\nextern const SKP_uint16 SKP_Silk_delta_gain_CDF[ MAX_DELTA_GAIN_QUANT - MIN_DELTA_GAIN_QUANT + 2 ]; /*  46 */\nextern const SKP_int    SKP_Silk_delta_gain_CDF_offset;\n\nextern const SKP_uint16 SKP_Silk_pitch_lag_NB_CDF[ 8 * ( PITCH_EST_MAX_LAG_MS - PITCH_EST_MIN_LAG_MS ) + 2 ];   /* 130 */\nextern const SKP_int    SKP_Silk_pitch_lag_NB_CDF_offset;\nextern const SKP_uint16 SKP_Silk_pitch_lag_MB_CDF[ 12 * ( PITCH_EST_MAX_LAG_MS - PITCH_EST_MIN_LAG_MS ) + 2 ];  /* 194 */\nextern const SKP_int    SKP_Silk_pitch_lag_MB_CDF_offset;\nextern const SKP_uint16 SKP_Silk_pitch_lag_WB_CDF[ 16 * ( PITCH_EST_MAX_LAG_MS - PITCH_EST_MIN_LAG_MS ) + 2 ];  /* 258 */\nextern const SKP_int    SKP_Silk_pitch_lag_WB_CDF_offset;\nextern const SKP_uint16 SKP_Silk_pitch_lag_SWB_CDF[ 24 * ( PITCH_EST_MAX_LAG_MS - PITCH_EST_MIN_LAG_MS ) + 2 ]; /* 386 */\nextern const SKP_int    SKP_Silk_pitch_lag_SWB_CDF_offset;\n\nextern const SKP_uint16 SKP_Silk_pitch_contour_CDF[ 35 ];                                           /*  35 */\nextern const SKP_int    SKP_Silk_pitch_contour_CDF_offset;\nextern const SKP_uint16 SKP_Silk_pitch_contour_NB_CDF[ 12 ];                                        /*  12 */\nextern const SKP_int    SKP_Silk_pitch_contour_NB_CDF_offset;\nextern const SKP_uint16 SKP_Silk_pitch_delta_CDF[23];                                               /* 23 */\nextern const SKP_int    SKP_Silk_pitch_delta_CDF_offset;\n\nextern const SKP_uint16 SKP_Silk_pulses_per_block_CDF[ N_RATE_LEVELS ][ MAX_PULSES + 3 ];           /* 210 */\nextern const SKP_int    SKP_Silk_pulses_per_block_CDF_offset;\nextern const SKP_int16  SKP_Silk_pulses_per_block_BITS_Q6[ N_RATE_LEVELS - 1 ][ MAX_PULSES + 2 ];   /* 180 */\n\nextern const SKP_uint16 SKP_Silk_rate_levels_CDF[ 2 ][ N_RATE_LEVELS ];                             /*  20 */\nextern const SKP_int    SKP_Silk_rate_levels_CDF_offset;\nextern const SKP_int16  SKP_Silk_rate_levels_BITS_Q6[ 2 ][ N_RATE_LEVELS - 1 ];                     /*  18 */\n\nextern const SKP_int    SKP_Silk_max_pulses_table[ 4 ];                                             /*   4 */\n\nextern const SKP_uint16 SKP_Silk_shell_code_table0[  33 ];                                          /*  33 */\nextern const SKP_uint16 SKP_Silk_shell_code_table1[  52 ];                                          /*  52 */\nextern const SKP_uint16 SKP_Silk_shell_code_table2[ 102 ];                                          /* 102 */\nextern const SKP_uint16 SKP_Silk_shell_code_table3[ 207 ];                                          /* 207 */\nextern const SKP_uint16 SKP_Silk_shell_code_table_offsets[ 19 ];                                    /*  19 */\n\nextern const SKP_uint16 SKP_Silk_lsb_CDF[ 3 ];                                                      /*   3 */\n\nextern const SKP_uint16 SKP_Silk_sign_CDF[ 36 ];                                                    /*  36 */\n\nextern const SKP_uint16 SKP_Silk_LTP_per_index_CDF[ 4 ];                                            /*   4 */\nextern const SKP_int    SKP_Silk_LTP_per_index_CDF_offset;\nextern const SKP_int16  * const SKP_Silk_LTP_gain_BITS_Q6_ptrs[ NB_LTP_CBKS ];                      /*   3 */\nextern const SKP_uint16 * const SKP_Silk_LTP_gain_CDF_ptrs[ NB_LTP_CBKS ];                          /*   3 */\nextern const SKP_int    SKP_Silk_LTP_gain_CDF_offsets[ NB_LTP_CBKS ];                               /*   3 */\nextern const SKP_int32  SKP_Silk_LTP_gain_middle_avg_RD_Q14;\nextern const SKP_uint16 SKP_Silk_LTPscale_CDF[ 4 ];                                                 /*   4 */\nextern const SKP_int    SKP_Silk_LTPscale_offset;\n\n/* Tables for LTPScale */\nextern const SKP_int16  SKP_Silk_LTPScales_table_Q14[ 3 ];\n\nextern const SKP_uint16 SKP_Silk_vadflag_CDF[ 3 ];                                                  /*   3 */\nextern const SKP_int    SKP_Silk_vadflag_offset;\n\nextern const SKP_int    SKP_Silk_SamplingRates_table[ 4 ];                                          /*   4 */\nextern const SKP_uint16 SKP_Silk_SamplingRates_CDF[ 5 ];                                            /*   5 */\nextern const SKP_int    SKP_Silk_SamplingRates_offset;\n\nextern const SKP_uint16 SKP_Silk_NLSF_interpolation_factor_CDF[ 6 ];\nextern const SKP_int    SKP_Silk_NLSF_interpolation_factor_offset;\n\n/* NLSF codebooks */\nextern const SKP_Silk_NLSF_CB_struct SKP_Silk_NLSF_CB0_16, SKP_Silk_NLSF_CB1_16;\nextern const SKP_Silk_NLSF_CB_struct SKP_Silk_NLSF_CB0_10, SKP_Silk_NLSF_CB1_10;\n\n/* quantization tables */\nextern const SKP_int16 * const SKP_Silk_LTP_vq_ptrs_Q14[ NB_LTP_CBKS ];                             /* 168 */\nextern const SKP_int    SKP_Silk_LTP_vq_sizes[ NB_LTP_CBKS ];                                       /*   3 */\n\n/* Piece-wise linear mapping from bitrate in kbps to coding quality in dB SNR */\nextern const SKP_int32  TargetRate_table_NB[  TARGET_RATE_TAB_SZ ];\nextern const SKP_int32  TargetRate_table_MB[  TARGET_RATE_TAB_SZ ];\nextern const SKP_int32  TargetRate_table_WB[  TARGET_RATE_TAB_SZ ];\nextern const SKP_int32  TargetRate_table_SWB[ TARGET_RATE_TAB_SZ ];\nextern const SKP_int32  SNR_table_Q1[         TARGET_RATE_TAB_SZ ];\n\nextern const SKP_int32  SNR_table_one_bit_per_sample_Q7[ 4 ];\n\n/* Filter coeficicnts for HP filter: 4. Order filter implementad as two biquad filters  */\nextern const SKP_int16  SKP_Silk_SWB_detect_B_HP_Q13[ NB_SOS ][ 3 ];\nextern const SKP_int16  SKP_Silk_SWB_detect_A_HP_Q13[ NB_SOS ][ 2 ];\n\n/* Decoder high-pass filter coefficients for 24 kHz sampling */\nextern const SKP_int16  SKP_Silk_Dec_A_HP_24[ DEC_HP_ORDER ];                                       /*   2 */\nextern const SKP_int16  SKP_Silk_Dec_B_HP_24[ DEC_HP_ORDER + 1 ];                                   /*   3 */\n\n/* Decoder high-pass filter coefficients for 16 kHz sampling */\nextern const SKP_int16  SKP_Silk_Dec_A_HP_16[ DEC_HP_ORDER ];                                       /*   2 */\nextern const SKP_int16  SKP_Silk_Dec_B_HP_16[ DEC_HP_ORDER + 1 ];                                   /*   3 */\n\n/* Decoder high-pass filter coefficients for 12 kHz sampling */\nextern const SKP_int16  SKP_Silk_Dec_A_HP_12[ DEC_HP_ORDER ];                                       /*   2 */\nextern const SKP_int16  SKP_Silk_Dec_B_HP_12[ DEC_HP_ORDER + 1 ];                                   /*   3 */\n\n/* Decoder high-pass filter coefficients for 8 kHz sampling */\nextern const SKP_int16  SKP_Silk_Dec_A_HP_8[ DEC_HP_ORDER ];                                        /*   2 */\nextern const SKP_int16  SKP_Silk_Dec_B_HP_8[ DEC_HP_ORDER + 1 ];                                    /*   3 */\n\n/* Table for frame termination indication */\nextern const SKP_uint16 SKP_Silk_FrameTermination_CDF[ 5 ];\nextern const SKP_int    SKP_Silk_FrameTermination_offset;\n\n/* Table for random seed */\nextern const SKP_uint16 SKP_Silk_Seed_CDF[ 5 ];\nextern const SKP_int    SKP_Silk_Seed_offset;\n\n/* Quantization offsets */\nextern const SKP_int16  SKP_Silk_Quantization_Offsets_Q10[ 2 ][ 2 ];\n\n#if SWITCH_TRANSITION_FILTERING\n/* Interpolation points for filter coefficients used in the bandwidth transition smoother */\nextern const SKP_int32 SKP_Silk_Transition_LP_B_Q28[ TRANSITION_INT_NUM ][ TRANSITION_NB ];\nextern const SKP_int32 SKP_Silk_Transition_LP_A_Q28[ TRANSITION_INT_NUM ][ TRANSITION_NA ];\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_tables_NLSF_CB0_10.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_TABLES_NLSF_CB0_10_H\n#define SKP_SILK_TABLES_NLSF_CB0_10_H\n\n#include \"SKP_Silk_define.h\"\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n#define NLSF_MSVQ_CB0_10_STAGES       6\n#define NLSF_MSVQ_CB0_10_VECTORS      120\n\n/* NLSF codebook entropy coding tables */\nextern const SKP_uint16         SKP_Silk_NLSF_MSVQ_CB0_10_CDF[ NLSF_MSVQ_CB0_10_VECTORS + NLSF_MSVQ_CB0_10_STAGES ];\nextern const SKP_uint16 * const SKP_Silk_NLSF_MSVQ_CB0_10_CDF_start_ptr[                  NLSF_MSVQ_CB0_10_STAGES ];\nextern const SKP_int            SKP_Silk_NLSF_MSVQ_CB0_10_CDF_middle_idx[                 NLSF_MSVQ_CB0_10_STAGES ];\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_tables_NLSF_CB0_16.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_TABLES_NLSF_CB0_16_H\n#define SKP_SILK_TABLES_NLSF_CB0_16_H\n\n#include \"SKP_Silk_define.h\"\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n#define NLSF_MSVQ_CB0_16_STAGES       10\n#define NLSF_MSVQ_CB0_16_VECTORS      216\n\n/* NLSF codebook entropy coding tables */\nextern const SKP_uint16         SKP_Silk_NLSF_MSVQ_CB0_16_CDF[ NLSF_MSVQ_CB0_16_VECTORS + NLSF_MSVQ_CB0_16_STAGES ];\nextern const SKP_uint16 * const SKP_Silk_NLSF_MSVQ_CB0_16_CDF_start_ptr[                  NLSF_MSVQ_CB0_16_STAGES ];\nextern const SKP_int            SKP_Silk_NLSF_MSVQ_CB0_16_CDF_middle_idx[                 NLSF_MSVQ_CB0_16_STAGES ];\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_tables_NLSF_CB1_10.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_TABLES_NLSF_CB1_10_H\n#define SKP_SILK_TABLES_NLSF_CB1_10_H\n\n#include \"SKP_Silk_define.h\"\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n#define NLSF_MSVQ_CB1_10_STAGES       6\n#define NLSF_MSVQ_CB1_10_VECTORS      72\n\n/* NLSF codebook entropy coding tables */\nextern const SKP_uint16         SKP_Silk_NLSF_MSVQ_CB1_10_CDF[ NLSF_MSVQ_CB1_10_VECTORS + NLSF_MSVQ_CB1_10_STAGES ];\nextern const SKP_uint16 * const SKP_Silk_NLSF_MSVQ_CB1_10_CDF_start_ptr[                  NLSF_MSVQ_CB1_10_STAGES ];\nextern const SKP_int            SKP_Silk_NLSF_MSVQ_CB1_10_CDF_middle_idx[                 NLSF_MSVQ_CB1_10_STAGES ];\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_tables_NLSF_CB1_16.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_TABLES_NLSF_CB1_16_H\n#define SKP_SILK_TABLES_NLSF_CB1_16_H\n\n#include \"SKP_Silk_define.h\"\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n#define NLSF_MSVQ_CB1_16_STAGES       10\n#define NLSF_MSVQ_CB1_16_VECTORS      104\n\n/* NLSF codebook entropy coding tables */\nextern const SKP_uint16         SKP_Silk_NLSF_MSVQ_CB1_16_CDF[ NLSF_MSVQ_CB1_16_VECTORS + NLSF_MSVQ_CB1_16_STAGES ];\nextern const SKP_uint16 * const SKP_Silk_NLSF_MSVQ_CB1_16_CDF_start_ptr[                  NLSF_MSVQ_CB1_16_STAGES ];\nextern const SKP_int            SKP_Silk_NLSF_MSVQ_CB1_16_CDF_middle_idx[                 NLSF_MSVQ_CB1_16_STAGES ];\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_tuning_parameters.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef SKP_SILK_TUNING_PARAMETERS_H\n#define SKP_SILK_TUNING_PARAMETERS_H\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif\n\n/*******************/\n/* Pitch estimator */\n/*******************/\n\n/* Level of noise floor for whitening filter LPC analysis in pitch analysis */\n#define FIND_PITCH_WHITE_NOISE_FRACTION                 1e-3f\n\n/* Bandwidth expansion for whitening filter in pitch analysis */\n#define FIND_PITCH_BANDWITH_EXPANSION                   0.99f\n\n/* Threshold used by pitch estimator for early escape */\n#define FIND_PITCH_CORRELATION_THRESHOLD_HC_MODE        0.7f\n#define FIND_PITCH_CORRELATION_THRESHOLD_MC_MODE        0.75f\n#define FIND_PITCH_CORRELATION_THRESHOLD_LC_MODE        0.8f\n\n/*********************/\n/* Linear prediction */\n/*********************/\n\n/* LPC analysis defines: regularization and bandwidth expansion */\n#define FIND_LPC_COND_FAC                               2.5e-5f\n#define FIND_LPC_CHIRP                                  0.99995f\n\n/* LTP analysis defines */\n#define FIND_LTP_COND_FAC                               1e-5f\n#define LTP_DAMPING                                     0.01f\n#define LTP_SMOOTHING                                   0.1f\n\n/* LTP quantization settings */\n#define MU_LTP_QUANT_NB                                 0.03f\n#define MU_LTP_QUANT_MB                                 0.025f\n#define MU_LTP_QUANT_WB                                 0.02f\n#define MU_LTP_QUANT_SWB                                0.016f\n\n/***********************/\n/* High pass filtering */\n/***********************/\n\n/* Smoothing parameters for low end of pitch frequency range estimation */\n#define VARIABLE_HP_SMTH_COEF1                          0.1f\n#define VARIABLE_HP_SMTH_COEF2                          0.015f\n\n/* Min and max values for low end of pitch frequency range estimation */\n#define VARIABLE_HP_MIN_FREQ                            80.0f\n#define VARIABLE_HP_MAX_FREQ                            150.0f\n\n/* Max absolute difference between log2 of pitch frequency and smoother state, to enter the smoother */\n#define VARIABLE_HP_MAX_DELTA_FREQ                      0.4f\n\n/***********/\n/* Various */\n/***********/\n\n/* Required speech activity for counting frame as active */\n#define WB_DETECT_ACTIVE_SPEECH_LEVEL_THRES             0.7f        \n\n#define SPEECH_ACTIVITY_DTX_THRES                       0.1f\n\n/* Speech Activity LBRR enable threshold (needs tuning) */\n#define LBRR_SPEECH_ACTIVITY_THRES                      0.5f        \n\n/*************************/\n/* Perceptual parameters */\n/*************************/\n\n/* reduction in coding SNR during low speech activity */\n#define BG_SNR_DECR_dB                                  4.0f\n\n/* factor for reducing quantization noise during voiced speech */\n#define HARM_SNR_INCR_dB                                2.0f\n\n/* factor for reducing quantization noise for unvoiced sparse signals */\n#define SPARSE_SNR_INCR_dB                              2.0f\n\n/* threshold for sparseness measure above which to use lower quantization offset during unvoiced */\n#define SPARSENESS_THRESHOLD_QNT_OFFSET                 0.75f\n\n/* warping control */\n#define WARPING_MULTIPLIER                              0.015f\n\n/* fraction added to first autocorrelation value */\n#define SHAPE_WHITE_NOISE_FRACTION                      1e-5f\n\n/* noise shaping filter chirp factor */\n#define BANDWIDTH_EXPANSION                             0.95f\n\n/* difference between chirp factors for analysis and synthesis noise shaping filters at low bitrates */\n#define LOW_RATE_BANDWIDTH_EXPANSION_DELTA              0.01f\n\n/* gain reduction for fricatives */\n#define DE_ESSER_COEF_SWB_dB                            2.0f\n#define DE_ESSER_COEF_WB_dB                             1.0f\n\n/* extra harmonic boosting (signal shaping) at low bitrates */\n#define LOW_RATE_HARMONIC_BOOST                         0.1f\n\n/* extra harmonic boosting (signal shaping) for noisy input signals */\n#define LOW_INPUT_QUALITY_HARMONIC_BOOST                0.1f\n\n/* harmonic noise shaping */\n#define HARMONIC_SHAPING                                0.3f\n\n/* extra harmonic noise shaping for high bitrates or noisy input */\n#define HIGH_RATE_OR_LOW_QUALITY_HARMONIC_SHAPING       0.2f\n\n/* parameter for shaping noise towards higher frequencies */\n#define HP_NOISE_COEF                                   0.3f\n\n/* parameter for shaping noise even more towards higher frequencies during voiced speech */\n#define HARM_HP_NOISE_COEF                              0.35f\n\n/* parameter for applying a high-pass tilt to the input signal */\n#define INPUT_TILT                                      0.05f\n\n/* parameter for extra high-pass tilt to the input signal at high rates */\n#define HIGH_RATE_INPUT_TILT                            0.1f\n\n/* parameter for reducing noise at the very low frequencies */\n#define LOW_FREQ_SHAPING                                3.0f\n\n/* less reduction of noise at the very low frequencies for signals with low SNR at low frequencies */\n#define LOW_QUALITY_LOW_FREQ_SHAPING_DECR               0.5f\n\n/* noise floor to put a lower limit on the quantization step size */\n#define NOISE_FLOOR_dB                                  4.0f\n\n/* noise floor relative to active speech gain level */\n#define RELATIVE_MIN_GAIN_dB                            -50.0f\n\n/* subframe smoothing coefficient for determining active speech gain level (lower -> more smoothing) */\n#define GAIN_SMOOTHING_COEF                             1e-3f\n\n/* subframe smoothing coefficient for HarmBoost, HarmShapeGain, Tilt (lower -> more smoothing) */\n#define SUBFR_SMTH_COEF                                 0.4f\n\n/* parameters defining the R/D tradeoff in the residual quantizer */\n#define LAMBDA_OFFSET                                   1.2f\n#define LAMBDA_SPEECH_ACT                               -0.3f\n#define LAMBDA_DELAYED_DECISIONS                        -0.05f\n#define LAMBDA_INPUT_QUALITY                            -0.2f\n#define LAMBDA_CODING_QUALITY                           -0.1f\n#define LAMBDA_QUANT_OFFSET                             1.5f\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // SKP_SILK_TUNING_PARAMETERS_H\n"
  },
  {
    "path": "app/jni/include/SKP_Silk_typedef.h",
    "content": "/***********************************************************************\nCopyright (c) 2006-2012, Skype Limited. All rights reserved. \nRedistribution and use in source and binary forms, with or without \nmodification, (subject to the limitations in the disclaimer below) \nare permitted provided that the following conditions are met:\n- Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n- Redistributions in binary form must reproduce the above copyright \nnotice, this list of conditions and the following disclaimer in the \ndocumentation and/or other materials provided with the distribution.\n- Neither the name of Skype Limited, nor the names of specific \ncontributors, may be used to endorse or promote products derived from \nthis software without specific prior written permission.\nNO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED \nBY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND \nCONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND \nFITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE \nCOPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, \nINCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\nNOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF \nUSE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE \nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n***********************************************************************/\n\n#ifndef _SKP_SILK_API_TYPDEF_H_\n#define _SKP_SILK_API_TYPDEF_H_\n\n#ifndef SKP_USE_DOUBLE_PRECISION_FLOATS\n#define SKP_USE_DOUBLE_PRECISION_FLOATS\t\t0\n#endif\n\n#include <float.h>\n#if defined( __GNUC__ )\n#include <stdint.h>\n#endif\n\n#define SKP_int         int                     /* used for counters etc; at least 16 bits */\n#ifdef __GNUC__\n# define SKP_int64      int64_t\n#else\n# define SKP_int64      long long\n#endif\n#define SKP_int32       int\n#define SKP_int16       short\n#define SKP_int8        signed char\n\n#define SKP_uint        unsigned int            /* used for counters etc; at least 16 bits */\n#ifdef __GNUC__\n# define SKP_uint64     uint64_t\n#else\n# define SKP_uint64     unsigned long long\n#endif\n#define SKP_uint32      unsigned int\n#define SKP_uint16      unsigned short\n#define SKP_uint8       unsigned char\n\n#define SKP_int_ptr_size intptr_t\n\n#if SKP_USE_DOUBLE_PRECISION_FLOATS\n# define SKP_float      double\n# define SKP_float_MAX  DBL_MAX\n#else\n# define SKP_float      float\n# define SKP_float_MAX  FLT_MAX\n#endif\n\n#define SKP_INLINE      static __inline\n\n#ifdef _WIN32\n# define SKP_STR_CASEINSENSITIVE_COMPARE(x, y) _stricmp(x, y)\n#else\n# define SKP_STR_CASEINSENSITIVE_COMPARE(x, y) strcasecmp(x, y)\n#endif \n\n#define\tSKP_int64_MAX\t((SKP_int64)0x7FFFFFFFFFFFFFFFLL)\t/*  2^63 - 1  */\n#define SKP_int64_MIN\t((SKP_int64)0x8000000000000000LL)\t/* -2^63\t */\n#define\tSKP_int32_MAX\t0x7FFFFFFF\t\t\t\t\t\t\t/*  2^31 - 1 =  2147483647*/\n#define SKP_int32_MIN\t((SKP_int32)0x80000000)\t\t\t\t/* -2^31\t = -2147483648*/\n#define\tSKP_int16_MAX\t0x7FFF\t\t\t\t\t\t\t\t/*\t2^15 - 1 =\t32767*/\n#define SKP_int16_MIN\t((SKP_int16)0x8000)\t\t\t\t\t/* -2^15\t = -32768*/\n#define\tSKP_int8_MAX\t0x7F\t\t\t\t\t\t\t\t/*\t2^7 - 1  =  127*/\n#define SKP_int8_MIN\t((SKP_int8)0x80)\t\t\t\t\t/* -2^7 \t = -128*/\n\n#define SKP_uint32_MAX\t0xFFFFFFFF\t/* 2^32 - 1 = 4294967295 */\n#define SKP_uint32_MIN\t0x00000000\n#define SKP_uint16_MAX\t0xFFFF\t\t/* 2^16 - 1 = 65535 */\n#define SKP_uint16_MIN\t0x0000\n#define SKP_uint8_MAX\t0xFF\t\t/*  2^8 - 1 = 255 */\n#define SKP_uint8_MIN\t0x00\n\n#define SKP_TRUE\t\t1\n#define SKP_FALSE\t\t0\n\n/* assertions */\n#if (defined _WIN32 && !defined _WINCE && !defined(__GNUC__) && !defined(NO_ASSERTS))\n# ifndef SKP_assert\n#  include <crtdbg.h>      /* ASSERTE() */\n#  define SKP_assert(COND)   _ASSERTE(COND)\n# endif\n#else\n# define SKP_assert(COND)\n#endif\n\n#endif\n"
  },
  {
    "path": "app/jni/include/lame.h",
    "content": "/*\n *\tInterface to MP3 LAME encoding engine\n *\n *\tCopyright (c) 1999 Mark Taylor\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: lame.h,v 1.189.2.1 2012/01/08 23:49:58 robert Exp $ */\n\n#ifndef LAME_LAME_H\n#define LAME_LAME_H\n\n/* for size_t typedef */\n#include <stddef.h>\n/* for va_list typedef */\n#include <stdarg.h>\n/* for FILE typedef, TODO: remove when removing lame_mp3_tags_fid */\n#include <stdio.h>\n\n//#if defined(__cplusplus)\n//extern \"C\" {\n//#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include \"stdlib.h\"\n\ntypedef void (*lame_report_function)(const char *format, va_list ap);\n\n#if defined(WIN32) || defined(_WIN32)\n#undef CDECL\n#define CDECL __cdecl\n#else\n#define CDECL\n#endif\n\n#define DEPRECATED_OR_OBSOLETE_CODE_REMOVED 1\n\ntypedef enum vbr_mode_e {\n  vbr_off=0,\n  vbr_mt,               /* obsolete, same as vbr_mtrh */\n  vbr_rh,\n  vbr_abr,\n  vbr_mtrh,\n  vbr_max_indicator,    /* Don't use this! It's used for sanity checks.       */\n  vbr_default=vbr_mtrh    /* change this to change the default VBR mode of LAME */\n} vbr_mode;\n\n\n/* MPEG modes */\ntypedef enum MPEG_mode_e {\n  STEREO = 0,\n  JOINT_STEREO,\n  DUAL_CHANNEL,   /* LAME doesn't supports this! */\n  MONO,\n  NOT_SET,\n  MAX_INDICATOR   /* Don't use this! It's used for sanity checks. */\n} MPEG_mode;\n\n/* Padding types */\ntypedef enum Padding_type_e {\n  PAD_NO = 0,\n  PAD_ALL,\n  PAD_ADJUST,\n  PAD_MAX_INDICATOR   /* Don't use this! It's used for sanity checks. */\n} Padding_type;\n\n\n\n/*presets*/\ntypedef enum preset_mode_e {\n    /*values from 8 to 320 should be reserved for abr bitrates*/\n    /*for abr I'd suggest to directly use the targeted bitrate as a value*/\n    ABR_8 = 8,\n    ABR_320 = 320,\n\n    V9 = 410, /*Vx to match Lame and VBR_xx to match FhG*/\n    VBR_10 = 410,\n    V8 = 420,\n    VBR_20 = 420,\n    V7 = 430,\n    VBR_30 = 430,\n    V6 = 440,\n    VBR_40 = 440,\n    V5 = 450,\n    VBR_50 = 450,\n    V4 = 460,\n    VBR_60 = 460,\n    V3 = 470,\n    VBR_70 = 470,\n    V2 = 480,\n    VBR_80 = 480,\n    V1 = 490,\n    VBR_90 = 490,\n    V0 = 500,\n    VBR_100 = 500,\n\n\n\n    /*still there for compatibility*/\n    R3MIX = 1000,\n    STANDARD = 1001,\n    EXTREME = 1002,\n    INSANE = 1003,\n    STANDARD_FAST = 1004,\n    EXTREME_FAST = 1005,\n    MEDIUM = 1006,\n    MEDIUM_FAST = 1007\n} preset_mode;\n\n\n/*asm optimizations*/\ntypedef enum asm_optimizations_e {\n    MMX = 1,\n    AMD_3DNOW = 2,\n    SSE = 3\n} asm_optimizations;\n\n\n/* psychoacoustic model */\ntypedef enum Psy_model_e {\n    PSY_GPSYCHO = 1,\n    PSY_NSPSYTUNE = 2\n} Psy_model;\n\n\n/* buffer considerations */\ntypedef enum buffer_constraint_e {\n    MDB_DEFAULT=0,\n    MDB_STRICT_ISO=1,\n    MDB_MAXIMUM=2\n} buffer_constraint;\n\n\nstruct lame_global_struct;\ntypedef struct lame_global_struct lame_global_flags;\ntypedef lame_global_flags *lame_t;\n\n\n\n\n/***********************************************************************\n *\n *  The LAME API\n *  These functions should be called, in this order, for each\n *  MP3 file to be encoded.  See the file \"API\" for more documentation\n *\n ***********************************************************************/\n\n\n/*\n * REQUIRED:\n * initialize the encoder.  sets default for all encoder parameters,\n * returns NULL if some malloc()'s failed\n * otherwise returns pointer to structure needed for all future\n * API calls.\n */\nlame_global_flags * CDECL lame_init(void);\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n#else\n/* obsolete version */\nint CDECL lame_init_old(lame_global_flags *);\n#endif\n\n/*\n * OPTIONAL:\n * set as needed to override defaults\n */\n\n/********************************************************************\n *  input stream description\n ***********************************************************************/\n/* number of samples.  default = 2^32-1   */\nint CDECL lame_set_num_samples(lame_global_flags *, unsigned long);\nunsigned long CDECL lame_get_num_samples(const lame_global_flags *);\n\n/* input sample rate in Hz.  default = 44100hz */\nint CDECL lame_set_in_samplerate(lame_global_flags *, int);\nint CDECL lame_get_in_samplerate(const lame_global_flags *);\n\n/* number of channels in input stream. default=2  */\nint CDECL lame_set_num_channels(lame_global_flags *, int);\nint CDECL lame_get_num_channels(const lame_global_flags *);\n\n/*\n  scale the input by this amount before encoding.  default=1\n  (not used by decoding routines)\n*/\nint CDECL lame_set_scale(lame_global_flags *, float);\nfloat CDECL lame_get_scale(const lame_global_flags *);\n\n/*\n  scale the channel 0 (left) input by this amount before encoding.  default=1\n  (not used by decoding routines)\n*/\nint CDECL lame_set_scale_left(lame_global_flags *, float);\nfloat CDECL lame_get_scale_left(const lame_global_flags *);\n\n/*\n  scale the channel 1 (right) input by this amount before encoding.  default=1\n  (not used by decoding routines)\n*/\nint CDECL lame_set_scale_right(lame_global_flags *, float);\nfloat CDECL lame_get_scale_right(const lame_global_flags *);\n\n/*\n  output sample rate in Hz.  default = 0, which means LAME picks best value\n  based on the amount of compression.  MPEG only allows:\n  MPEG1    32, 44.1,   48khz\n  MPEG2    16, 22.05,  24\n  MPEG2.5   8, 11.025, 12\n  (not used by decoding routines)\n*/\nint CDECL lame_set_out_samplerate(lame_global_flags *, int);\nint CDECL lame_get_out_samplerate(const lame_global_flags *);\n\n\n/********************************************************************\n *  general control parameters\n ***********************************************************************/\n/* 1=cause LAME to collect data for an MP3 frame analyzer. default=0 */\nint CDECL lame_set_analysis(lame_global_flags *, int);\nint CDECL lame_get_analysis(const lame_global_flags *);\n\n/*\n  1 = write a Xing VBR header frame.\n  default = 1\n  this variable must have been added by a Hungarian notation Windows programmer :-)\n*/\nint CDECL lame_set_bWriteVbrTag(lame_global_flags *, int);\nint CDECL lame_get_bWriteVbrTag(const lame_global_flags *);\n\n/* 1=decode only.  use lame/mpglib to convert mp3/ogg to wav.  default=0 */\nint CDECL lame_set_decode_only(lame_global_flags *, int);\nint CDECL lame_get_decode_only(const lame_global_flags *);\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n#else\n/* 1=encode a Vorbis .ogg file.  default=0 */\n/* DEPRECATED */\nint CDECL lame_set_ogg(lame_global_flags *, int);\nint CDECL lame_get_ogg(const lame_global_flags *);\n#endif\n\n/*\n  internal algorithm selection.  True quality is determined by the bitrate\n  but this variable will effect quality by selecting expensive or cheap algorithms.\n  quality=0..9.  0=best (very slow).  9=worst.\n  recommended:  2     near-best quality, not too slow\n                5     good quality, fast\n                7     ok quality, really fast\n*/\nint CDECL lame_set_quality(lame_global_flags *, int);\nint CDECL lame_get_quality(const lame_global_flags *);\n\n/*\n  mode = 0,1,2,3 = stereo, jstereo, dual channel (not supported), mono\n  default: lame picks based on compression ration and input channels\n*/\nint CDECL lame_set_mode(lame_global_flags *, MPEG_mode);\nMPEG_mode CDECL lame_get_mode(const lame_global_flags *);\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n#else\n/*\n  mode_automs.  Use a M/S mode with a switching threshold based on\n  compression ratio\n  DEPRECATED\n*/\nint CDECL lame_set_mode_automs(lame_global_flags *, int);\nint CDECL lame_get_mode_automs(const lame_global_flags *);\n#endif\n\n/*\n  force_ms.  Force M/S for all frames.  For testing only.\n  default = 0 (disabled)\n*/\nint CDECL lame_set_force_ms(lame_global_flags *, int);\nint CDECL lame_get_force_ms(const lame_global_flags *);\n\n/* use free_format?  default = 0 (disabled) */\nint CDECL lame_set_free_format(lame_global_flags *, int);\nint CDECL lame_get_free_format(const lame_global_flags *);\n\n/* perform ReplayGain analysis?  default = 0 (disabled) */\nint CDECL lame_set_findReplayGain(lame_global_flags *, int);\nint CDECL lame_get_findReplayGain(const lame_global_flags *);\n\n/* decode on the fly. Search for the peak sample. If the ReplayGain\n * analysis is enabled then perform the analysis on the decoded data\n * stream. default = 0 (disabled)\n * NOTE: if this option is set the build-in decoder should not be used */\nint CDECL lame_set_decode_on_the_fly(lame_global_flags *, int);\nint CDECL lame_get_decode_on_the_fly(const lame_global_flags *);\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n#else\n/* DEPRECATED: now does the same as lame_set_findReplayGain()\n   default = 0 (disabled) */\nint CDECL lame_set_ReplayGain_input(lame_global_flags *, int);\nint CDECL lame_get_ReplayGain_input(const lame_global_flags *);\n\n/* DEPRECATED: now does the same as\n   lame_set_decode_on_the_fly() && lame_set_findReplayGain()\n   default = 0 (disabled) */\nint CDECL lame_set_ReplayGain_decode(lame_global_flags *, int);\nint CDECL lame_get_ReplayGain_decode(const lame_global_flags *);\n\n/* DEPRECATED: now does the same as lame_set_decode_on_the_fly()\n   default = 0 (disabled) */\nint CDECL lame_set_findPeakSample(lame_global_flags *, int);\nint CDECL lame_get_findPeakSample(const lame_global_flags *);\n#endif\n\n/* counters for gapless encoding */\nint CDECL lame_set_nogap_total(lame_global_flags*, int);\nint CDECL lame_get_nogap_total(const lame_global_flags*);\n\nint CDECL lame_set_nogap_currentindex(lame_global_flags* , int);\nint CDECL lame_get_nogap_currentindex(const lame_global_flags*);\n\n\n/*\n * OPTIONAL:\n * Set printf like error/debug/message reporting functions.\n * The second argument has to be a pointer to a function which looks like\n *   void my_debugf(const char *format, va_list ap)\n *   {\n *       (void) vfprintf(stdout, format, ap);\n *   }\n * If you use NULL as the value of the pointer in the set function, the\n * lame buildin function will be used (prints to stderr).\n * To quiet any output you have to replace the body of the example function\n * with just \"return;\" and use it in the set function.\n */\nint CDECL lame_set_errorf(lame_global_flags *, lame_report_function);\nint CDECL lame_set_debugf(lame_global_flags *, lame_report_function);\nint CDECL lame_set_msgf  (lame_global_flags *, lame_report_function);\n\n\n\n/* set one of brate compression ratio.  default is compression ratio of 11.  */\nint CDECL lame_set_brate(lame_global_flags *, int);\nint CDECL lame_get_brate(const lame_global_flags *);\nint CDECL lame_set_compression_ratio(lame_global_flags *, float);\nfloat CDECL lame_get_compression_ratio(const lame_global_flags *);\n\n\nint CDECL lame_set_preset( lame_global_flags*  gfp, int );\nint CDECL lame_set_asm_optimizations( lame_global_flags*  gfp, int, int );\n\n\n\n/********************************************************************\n *  frame params\n ***********************************************************************/\n/* mark as copyright.  default=0 */\nint CDECL lame_set_copyright(lame_global_flags *, int);\nint CDECL lame_get_copyright(const lame_global_flags *);\n\n/* mark as original.  default=1 */\nint CDECL lame_set_original(lame_global_flags *, int);\nint CDECL lame_get_original(const lame_global_flags *);\n\n/* error_protection.  Use 2 bytes from each frame for CRC checksum. default=0 */\nint CDECL lame_set_error_protection(lame_global_flags *, int);\nint CDECL lame_get_error_protection(const lame_global_flags *);\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n#else\n/* padding_type. 0=pad no frames  1=pad all frames 2=adjust padding(default) */\nint CDECL lame_set_padding_type(lame_global_flags *, Padding_type);\nPadding_type CDECL lame_get_padding_type(const lame_global_flags *);\n#endif\n\n/* MP3 'private extension' bit  Meaningless.  default=0 */\nint CDECL lame_set_extension(lame_global_flags *, int);\nint CDECL lame_get_extension(const lame_global_flags *);\n\n/* enforce strict ISO compliance.  default=0 */\nint CDECL lame_set_strict_ISO(lame_global_flags *, int);\nint CDECL lame_get_strict_ISO(const lame_global_flags *);\n\n\n/********************************************************************\n * quantization/noise shaping\n ***********************************************************************/\n\n/* disable the bit reservoir. For testing only. default=0 */\nint CDECL lame_set_disable_reservoir(lame_global_flags *, int);\nint CDECL lame_get_disable_reservoir(const lame_global_flags *);\n\n/* select a different \"best quantization\" function. default=0  */\nint CDECL lame_set_quant_comp(lame_global_flags *, int);\nint CDECL lame_get_quant_comp(const lame_global_flags *);\nint CDECL lame_set_quant_comp_short(lame_global_flags *, int);\nint CDECL lame_get_quant_comp_short(const lame_global_flags *);\n\nint CDECL lame_set_experimentalX(lame_global_flags *, int); /* compatibility*/\nint CDECL lame_get_experimentalX(const lame_global_flags *);\n\n/* another experimental option.  for testing only */\nint CDECL lame_set_experimentalY(lame_global_flags *, int);\nint CDECL lame_get_experimentalY(const lame_global_flags *);\n\n/* another experimental option.  for testing only */\nint CDECL lame_set_experimentalZ(lame_global_flags *, int);\nint CDECL lame_get_experimentalZ(const lame_global_flags *);\n\n/* Naoki's psycho acoustic model.  default=0 */\nint CDECL lame_set_exp_nspsytune(lame_global_flags *, int);\nint CDECL lame_get_exp_nspsytune(const lame_global_flags *);\n\nvoid CDECL lame_set_msfix(lame_global_flags *, double);\nfloat CDECL lame_get_msfix(const lame_global_flags *);\n\n\n/********************************************************************\n * VBR control\n ***********************************************************************/\n/* Types of VBR.  default = vbr_off = CBR */\nint CDECL lame_set_VBR(lame_global_flags *, vbr_mode);\nvbr_mode CDECL lame_get_VBR(const lame_global_flags *);\n\n/* VBR quality level.  0=highest  9=lowest  */\nint CDECL lame_set_VBR_q(lame_global_flags *, int);\nint CDECL lame_get_VBR_q(const lame_global_flags *);\n\n/* VBR quality level.  0=highest  9=lowest, Range [0,...,10[  */\nint CDECL lame_set_VBR_quality(lame_global_flags *, float);\nfloat CDECL lame_get_VBR_quality(const lame_global_flags *);\n\n/* Ignored except for VBR=vbr_abr (ABR mode) */\nint CDECL lame_set_VBR_mean_bitrate_kbps(lame_global_flags *, int);\nint CDECL lame_get_VBR_mean_bitrate_kbps(const lame_global_flags *);\n\nint CDECL lame_set_VBR_min_bitrate_kbps(lame_global_flags *, int);\nint CDECL lame_get_VBR_min_bitrate_kbps(const lame_global_flags *);\n\nint CDECL lame_set_VBR_max_bitrate_kbps(lame_global_flags *, int);\nint CDECL lame_get_VBR_max_bitrate_kbps(const lame_global_flags *);\n\n/*\n  1=strictly enforce VBR_min_bitrate.  Normally it will be violated for\n  analog silence\n*/\nint CDECL lame_set_VBR_hard_min(lame_global_flags *, int);\nint CDECL lame_get_VBR_hard_min(const lame_global_flags *);\n\n/* for preset */\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n#else\nint CDECL lame_set_preset_expopts(lame_global_flags *, int);\n#endif\n\n/********************************************************************\n * Filtering control\n ***********************************************************************/\n/* freq in Hz to apply lowpass. Default = 0 = lame chooses.  -1 = disabled */\nint CDECL lame_set_lowpassfreq(lame_global_flags *, int);\nint CDECL lame_get_lowpassfreq(const lame_global_flags *);\n/* width of transition band, in Hz.  Default = one polyphase filter band */\nint CDECL lame_set_lowpasswidth(lame_global_flags *, int);\nint CDECL lame_get_lowpasswidth(const lame_global_flags *);\n\n/* freq in Hz to apply highpass. Default = 0 = lame chooses.  -1 = disabled */\nint CDECL lame_set_highpassfreq(lame_global_flags *, int);\nint CDECL lame_get_highpassfreq(const lame_global_flags *);\n/* width of transition band, in Hz.  Default = one polyphase filter band */\nint CDECL lame_set_highpasswidth(lame_global_flags *, int);\nint CDECL lame_get_highpasswidth(const lame_global_flags *);\n\n\n/********************************************************************\n * psycho acoustics and other arguments which you should not change\n * unless you know what you are doing\n ***********************************************************************/\n\n/* only use ATH for masking */\nint CDECL lame_set_ATHonly(lame_global_flags *, int);\nint CDECL lame_get_ATHonly(const lame_global_flags *);\n\n/* only use ATH for short blocks */\nint CDECL lame_set_ATHshort(lame_global_flags *, int);\nint CDECL lame_get_ATHshort(const lame_global_flags *);\n\n/* disable ATH */\nint CDECL lame_set_noATH(lame_global_flags *, int);\nint CDECL lame_get_noATH(const lame_global_flags *);\n\n/* select ATH formula */\nint CDECL lame_set_ATHtype(lame_global_flags *, int);\nint CDECL lame_get_ATHtype(const lame_global_flags *);\n\n/* lower ATH by this many db */\nint CDECL lame_set_ATHlower(lame_global_flags *, float);\nfloat CDECL lame_get_ATHlower(const lame_global_flags *);\n\n/* select ATH adaptive adjustment type */\nint CDECL lame_set_athaa_type( lame_global_flags *, int);\nint CDECL lame_get_athaa_type( const lame_global_flags *);\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n#else\n/* select the loudness approximation used by the ATH adaptive auto-leveling  */\nint CDECL lame_set_athaa_loudapprox( lame_global_flags *, int);\nint CDECL lame_get_athaa_loudapprox( const lame_global_flags *);\n#endif\n\n/* adjust (in dB) the point below which adaptive ATH level adjustment occurs */\nint CDECL lame_set_athaa_sensitivity( lame_global_flags *, float);\nfloat CDECL lame_get_athaa_sensitivity( const lame_global_flags* );\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n#else\n/* OBSOLETE: predictability limit (ISO tonality formula) */\nint CDECL lame_set_cwlimit(lame_global_flags *, int);\nint CDECL lame_get_cwlimit(const lame_global_flags *);\n#endif\n\n/*\n  allow blocktypes to differ between channels?\n  default: 0 for jstereo, 1 for stereo\n*/\nint CDECL lame_set_allow_diff_short(lame_global_flags *, int);\nint CDECL lame_get_allow_diff_short(const lame_global_flags *);\n\n/* use temporal masking effect (default = 1) */\nint CDECL lame_set_useTemporal(lame_global_flags *, int);\nint CDECL lame_get_useTemporal(const lame_global_flags *);\n\n/* use temporal masking effect (default = 1) */\nint CDECL lame_set_interChRatio(lame_global_flags *, float);\nfloat CDECL lame_get_interChRatio(const lame_global_flags *);\n\n/* disable short blocks */\nint CDECL lame_set_no_short_blocks(lame_global_flags *, int);\nint CDECL lame_get_no_short_blocks(const lame_global_flags *);\n\n/* force short blocks */\nint CDECL lame_set_force_short_blocks(lame_global_flags *, int);\nint CDECL lame_get_force_short_blocks(const lame_global_flags *);\n\n/* Input PCM is emphased PCM (for instance from one of the rarely\n   emphased CDs), it is STRONGLY not recommended to use this, because\n   psycho does not take it into account, and last but not least many decoders\n   ignore these bits */\nint CDECL lame_set_emphasis(lame_global_flags *, int);\nint CDECL lame_get_emphasis(const lame_global_flags *);\n\n\n\n/************************************************************************/\n/* internal variables, cannot be set...                                 */\n/* provided because they may be of use to calling application           */\n/************************************************************************/\n/* version  0=MPEG-2  1=MPEG-1  (2=MPEG-2.5)     */\nint CDECL lame_get_version(const lame_global_flags *);\n\n/* encoder delay   */\nint CDECL lame_get_encoder_delay(const lame_global_flags *);\n\n/*\n  padding appended to the input to make sure decoder can fully decode\n  all input.  Note that this value can only be calculated during the\n  call to lame_encoder_flush().  Before lame_encoder_flush() has\n  been called, the value of encoder_padding = 0.\n*/\nint CDECL lame_get_encoder_padding(const lame_global_flags *);\n\n/* size of MPEG frame */\nint CDECL lame_get_framesize(const lame_global_flags *);\n\n/* number of PCM samples buffered, but not yet encoded to mp3 data. */\nint CDECL lame_get_mf_samples_to_encode( const lame_global_flags*  gfp );\n\n/*\n  size (bytes) of mp3 data buffered, but not yet encoded.\n  this is the number of bytes which would be output by a call to\n  lame_encode_flush_nogap.  NOTE: lame_encode_flush() will return\n  more bytes than this because it will encode the reamining buffered\n  PCM samples before flushing the mp3 buffers.\n*/\nint CDECL lame_get_size_mp3buffer( const lame_global_flags*  gfp );\n\n/* number of frames encoded so far */\nint CDECL lame_get_frameNum(const lame_global_flags *);\n\n/*\n  lame's estimate of the total number of frames to be encoded\n   only valid if calling program set num_samples\n*/\nint CDECL lame_get_totalframes(const lame_global_flags *);\n\n/* RadioGain value. Multiplied by 10 and rounded to the nearest. */\nint CDECL lame_get_RadioGain(const lame_global_flags *);\n\n/* AudiophileGain value. Multipled by 10 and rounded to the nearest. */\nint CDECL lame_get_AudiophileGain(const lame_global_flags *);\n\n/* the peak sample */\nfloat CDECL lame_get_PeakSample(const lame_global_flags *);\n\n/* Gain change required for preventing clipping. The value is correct only if\n   peak sample searching was enabled. If negative then the waveform\n   already does not clip. The value is multiplied by 10 and rounded up. */\nint CDECL lame_get_noclipGainChange(const lame_global_flags *);\n\n/* user-specified scale factor required for preventing clipping. Value is\n   correct only if peak sample searching was enabled and no user-specified\n   scaling was performed. If negative then either the waveform already does\n   not clip or the value cannot be determined */\nfloat CDECL lame_get_noclipScale(const lame_global_flags *);\n\n\n\n\n\n\n\n/*\n * REQUIRED:\n * sets more internal configuration based on data provided above.\n * returns -1 if something failed.\n */\nint CDECL lame_init_params(lame_global_flags *);\n\n\n/*\n * OPTIONAL:\n * get the version number, in a string. of the form:\n * \"3.63 (beta)\" or just \"3.63\".\n */\nconst char*  CDECL get_lame_version       ( void );\nconst char*  CDECL get_lame_short_version ( void );\nconst char*  CDECL get_lame_very_short_version ( void );\nconst char*  CDECL get_psy_version        ( void );\nconst char*  CDECL get_lame_url           ( void );\nconst char*  CDECL get_lame_os_bitness    ( void );\n\n/*\n * OPTIONAL:\n * get the version numbers in numerical form.\n */\ntypedef struct {\n    /* generic LAME version */\n    int major;\n    int minor;\n    int alpha;               /* 0 if not an alpha version                  */\n    int beta;                /* 0 if not a beta version                    */\n\n    /* version of the psy model */\n    int psy_major;\n    int psy_minor;\n    int psy_alpha;           /* 0 if not an alpha version                  */\n    int psy_beta;            /* 0 if not a beta version                    */\n\n    /* compile time features */\n    const char *features;    /* Don't make assumptions about the contents! */\n} lame_version_t;\nvoid CDECL get_lame_version_numerical(lame_version_t *);\n\n\n/*\n * OPTIONAL:\n * print internal lame configuration to message handler\n */\nvoid CDECL lame_print_config(const lame_global_flags*  gfp);\n\nvoid CDECL lame_print_internals( const lame_global_flags *gfp);\n\n\n/*\n * input pcm data, output (maybe) mp3 frames.\n * This routine handles all buffering, resampling and filtering for you.\n *\n * return code     number of bytes output in mp3buf. Can be 0\n *                 -1:  mp3buf was too small\n *                 -2:  malloc() problem\n *                 -3:  lame_init_params() not called\n *                 -4:  psycho acoustic problems\n *\n * The required mp3buf_size can be computed from num_samples,\n * samplerate and encoding rate, but here is a worst case estimate:\n *\n * mp3buf_size in bytes = 1.25*num_samples + 7200\n *\n * I think a tighter bound could be:  (mt, March 2000)\n * MPEG1:\n *    num_samples*(bitrate/8)/samplerate + 4*1152*(bitrate/8)/samplerate + 512\n * MPEG2:\n *    num_samples*(bitrate/8)/samplerate + 4*576*(bitrate/8)/samplerate + 256\n *\n * but test first if you use that!\n *\n * set mp3buf_size = 0 and LAME will not check if mp3buf_size is\n * large enough.\n *\n * NOTE:\n * if gfp->num_channels=2, but gfp->mode = 3 (mono), the L & R channels\n * will be averaged into the L channel before encoding only the L channel\n * This will overwrite the data in buffer_l[] and buffer_r[].\n *\n*/\nint CDECL lame_encode_buffer (\n        lame_global_flags*  gfp,           /* global context handle         */\n        const short int     buffer_l [],   /* PCM data for left channel     */\n        const short int     buffer_r [],   /* PCM data for right channel    */\n        const int           nsamples,      /* number of samples per channel */\n        unsigned char*      mp3buf,        /* pointer to encoded MP3 stream */\n        const int           mp3buf_size ); /* number of valid octets in this\n                                              stream                        */\n\n/*\n * as above, but input has L & R channel data interleaved.\n * NOTE:\n * num_samples = number of samples in the L (or R)\n * channel, not the total number of samples in pcm[]\n */\nint CDECL lame_encode_buffer_interleaved(\n        lame_global_flags*  gfp,           /* global context handlei        */\n        short int           pcm[],         /* PCM data for left and right\n                                              channel, interleaved          */\n        int                 num_samples,   /* number of samples per channel,\n                                              _not_ number of samples in\n                                              pcm[]                         */\n        unsigned char*      mp3buf,        /* pointer to encoded MP3 stream */\n        int                 mp3buf_size ); /* number of valid octets in this\n                                              stream                        */\n\n\n/* as lame_encode_buffer, but for 'float's.\n * !! NOTE: !! data must still be scaled to be in the same range as\n * short int, +/- 32768\n */\nint CDECL lame_encode_buffer_float(\n        lame_global_flags*  gfp,           /* global context handle         */\n        const float         pcm_l [],      /* PCM data for left channel     */\n        const float         pcm_r [],      /* PCM data for right channel    */\n        const int           nsamples,      /* number of samples per channel */\n        unsigned char*      mp3buf,        /* pointer to encoded MP3 stream */\n        const int           mp3buf_size ); /* number of valid octets in this\n                                              stream                        */\n\n/* as lame_encode_buffer, but for 'float's.\n * !! NOTE: !! data must be scaled to +/- 1 full scale\n */\nint CDECL lame_encode_buffer_ieee_float(\n        lame_t          gfp,\n        const float     pcm_l [],          /* PCM data for left channel     */\n        const float     pcm_r [],          /* PCM data for right channel    */\n        const int       nsamples,\n        unsigned char * mp3buf,\n        const int       mp3buf_size);\nint CDECL lame_encode_buffer_interleaved_ieee_float(\n        lame_t          gfp,\n        const float     pcm[],             /* PCM data for left and right\n                                              channel, interleaved          */\n        const int       nsamples,\n        unsigned char * mp3buf,\n        const int       mp3buf_size);\n\n/* as lame_encode_buffer, but for 'double's.\n * !! NOTE: !! data must be scaled to +/- 1 full scale\n */\nint CDECL lame_encode_buffer_ieee_double(\n        lame_t          gfp,\n        const double    pcm_l [],          /* PCM data for left channel     */\n        const double    pcm_r [],          /* PCM data for right channel    */\n        const int       nsamples,\n        unsigned char * mp3buf,\n        const int       mp3buf_size);\nint CDECL lame_encode_buffer_interleaved_ieee_double(\n        lame_t          gfp,\n        const double    pcm[],             /* PCM data for left and right\n                                              channel, interleaved          */\n        const int       nsamples,\n        unsigned char * mp3buf,\n        const int       mp3buf_size);\n\n/* as lame_encode_buffer, but for long's\n * !! NOTE: !! data must still be scaled to be in the same range as\n * short int, +/- 32768\n *\n * This scaling was a mistake (doesn't allow one to exploit full\n * precision of type 'long'.  Use lame_encode_buffer_long2() instead.\n *\n */\nint CDECL lame_encode_buffer_long(\n        lame_global_flags*  gfp,           /* global context handle         */\n        const long     buffer_l [],       /* PCM data for left channel     */\n        const long     buffer_r [],       /* PCM data for right channel    */\n        const int           nsamples,      /* number of samples per channel */\n        unsigned char*      mp3buf,        /* pointer to encoded MP3 stream */\n        const int           mp3buf_size ); /* number of valid octets in this\n                                              stream                        */\n\n/* Same as lame_encode_buffer_long(), but with correct scaling.\n * !! NOTE: !! data must still be scaled to be in the same range as\n * type 'long'.   Data should be in the range:  +/- 2^(8*size(long)-1)\n *\n */\nint CDECL lame_encode_buffer_long2(\n        lame_global_flags*  gfp,           /* global context handle         */\n        const long     buffer_l [],       /* PCM data for left channel     */\n        const long     buffer_r [],       /* PCM data for right channel    */\n        const int           nsamples,      /* number of samples per channel */\n        unsigned char*      mp3buf,        /* pointer to encoded MP3 stream */\n        const int           mp3buf_size ); /* number of valid octets in this\n                                              stream                        */\n\n/* as lame_encode_buffer, but for int's\n * !! NOTE: !! input should be scaled to the maximum range of 'int'\n * If int is 4 bytes, then the values should range from\n * +/- 2147483648.\n *\n * This routine does not (and cannot, without loosing precision) use\n * the same scaling as the rest of the lame_encode_buffer() routines.\n *\n */\nint CDECL lame_encode_buffer_int(\n        lame_global_flags*  gfp,           /* global context handle         */\n        const int      buffer_l [],       /* PCM data for left channel     */\n        const int      buffer_r [],       /* PCM data for right channel    */\n        const int           nsamples,      /* number of samples per channel */\n        unsigned char*      mp3buf,        /* pointer to encoded MP3 stream */\n        const int           mp3buf_size ); /* number of valid octets in this\n                                              stream                        */\n\n\n\n\n\n/*\n * REQUIRED:\n * lame_encode_flush will flush the intenal PCM buffers, padding with\n * 0's to make sure the final frame is complete, and then flush\n * the internal MP3 buffers, and thus may return a\n * final few mp3 frames.  'mp3buf' should be at least 7200 bytes long\n * to hold all possible emitted data.\n *\n * will also write id3v1 tags (if any) into the bitstream\n *\n * return code = number of bytes output to mp3buf. Can be 0\n */\nint CDECL lame_encode_flush(\n        lame_global_flags *  gfp,    /* global context handle                 */\n        unsigned char*       mp3buf, /* pointer to encoded MP3 stream         */\n        int                  size);  /* number of valid octets in this stream */\n\n/*\n * OPTIONAL:\n * lame_encode_flush_nogap will flush the internal mp3 buffers and pad\n * the last frame with ancillary data so it is a complete mp3 frame.\n *\n * 'mp3buf' should be at least 7200 bytes long\n * to hold all possible emitted data.\n *\n * After a call to this routine, the outputed mp3 data is complete, but\n * you may continue to encode new PCM samples and write future mp3 data\n * to a different file.  The two mp3 files will play back with no gaps\n * if they are concatenated together.\n *\n * This routine will NOT write id3v1 tags into the bitstream.\n *\n * return code = number of bytes output to mp3buf. Can be 0\n */\nint CDECL lame_encode_flush_nogap(\n        lame_global_flags *  gfp,    /* global context handle                 */\n        unsigned char*       mp3buf, /* pointer to encoded MP3 stream         */\n        int                  size);  /* number of valid octets in this stream */\n\n/*\n * OPTIONAL:\n * Normally, this is called by lame_init_params().  It writes id3v2 and\n * Xing headers into the front of the bitstream, and sets frame counters\n * and bitrate histogram data to 0.  You can also call this after\n * lame_encode_flush_nogap().\n */\nint CDECL lame_init_bitstream(\n        lame_global_flags *  gfp);    /* global context handle                 */\n\n\n\n/*\n * OPTIONAL:    some simple statistics\n * a bitrate histogram to visualize the distribution of used frame sizes\n * a stereo mode histogram to visualize the distribution of used stereo\n *   modes, useful in joint-stereo mode only\n *   0: LR    left-right encoded\n *   1: LR-I  left-right and intensity encoded (currently not supported)\n *   2: MS    mid-side encoded\n *   3: MS-I  mid-side and intensity encoded (currently not supported)\n *\n * attention: don't call them after lame_encode_finish\n * suggested: lame_encode_flush -> lame_*_hist -> lame_close\n */\n\nvoid CDECL lame_bitrate_hist(\n        const lame_global_flags * gfp,\n        int bitrate_count[14] );\nvoid CDECL lame_bitrate_kbps(\n        const lame_global_flags * gfp,\n        int bitrate_kbps [14] );\nvoid CDECL lame_stereo_mode_hist(\n        const lame_global_flags * gfp,\n        int stereo_mode_count[4] );\n\nvoid CDECL lame_bitrate_stereo_mode_hist (\n        const lame_global_flags * gfp,\n        int bitrate_stmode_count[14][4] );\n\nvoid CDECL lame_block_type_hist (\n        const lame_global_flags * gfp,\n        int btype_count[6] );\n\nvoid CDECL lame_bitrate_block_type_hist (\n        const lame_global_flags * gfp,\n        int bitrate_btype_count[14][6] );\n\n#if (DEPRECATED_OR_OBSOLETE_CODE_REMOVED && 0)\n#else\n/*\n * OPTIONAL:\n * lame_mp3_tags_fid will rewrite a Xing VBR tag to the mp3 file with file\n * pointer fid.  These calls perform forward and backwards seeks, so make\n * sure fid is a real file.  Make sure lame_encode_flush has been called,\n * and all mp3 data has been written to the file before calling this\n * function.\n * NOTE:\n * if VBR  tags are turned off by the user, or turned off by LAME because\n * the output is not a regular file, this call does nothing\n * NOTE:\n * LAME wants to read from the file to skip an optional ID3v2 tag, so\n * make sure you opened the file for writing and reading.\n * NOTE:\n * You can call lame_get_lametag_frame instead, if you want to insert\n * the lametag yourself.\n*/\nvoid CDECL lame_mp3_tags_fid(lame_global_flags *, FILE* fid);\n#endif\n\n/*\n * OPTIONAL:\n * lame_get_lametag_frame copies the final LAME-tag into 'buffer'.\n * The function returns the number of bytes copied into buffer, or\n * the required buffer size, if the provided buffer is too small.\n * Function failed, if the return value is larger than 'size'!\n * Make sure lame_encode flush has been called before calling this function.\n * NOTE:\n * if VBR  tags are turned off by the user, or turned off by LAME,\n * this call does nothing and returns 0.\n * NOTE:\n * LAME inserted an empty frame in the beginning of mp3 audio data,\n * which you have to replace by the final LAME-tag frame after encoding.\n * In case there is no ID3v2 tag, usually this frame will be the very first\n * data in your mp3 file. If you put some other leading data into your\n * file, you'll have to do some bookkeeping about where to write this buffer.\n */\nsize_t CDECL lame_get_lametag_frame(\n        const lame_global_flags *, unsigned char* buffer, size_t size);\n\n/*\n * REQUIRED:\n * final call to free all remaining buffers\n */\nint  CDECL lame_close (lame_global_flags *);\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n#else\n/*\n * OBSOLETE:\n * lame_encode_finish combines lame_encode_flush() and lame_close() in\n * one call.  However, once this call is made, the statistics routines\n * will no longer work because the data will have been cleared, and\n * lame_mp3_tags_fid() cannot be called to add data to the VBR header\n */\nint CDECL lame_encode_finish(\n        lame_global_flags*  gfp,\n        unsigned char*      mp3buf,\n        int                 size );\n#endif\n\n\n\n\n\n\n/*********************************************************************\n *\n * decoding\n *\n * a simple interface to mpglib, part of mpg123, is also included if\n * libmp3lame is compiled with HAVE_MPGLIB\n *\n *********************************************************************/\n\nstruct hip_global_struct;\ntypedef struct hip_global_struct hip_global_flags;\ntypedef hip_global_flags *hip_t;\n\n\ntypedef struct {\n  int header_parsed;   /* 1 if header was parsed and following data was\n                          computed                                       */\n  int stereo;          /* number of channels                             */\n  int samplerate;      /* sample rate                                    */\n  int bitrate;         /* bitrate                                        */\n  int mode;            /* mp3 frame type                                 */\n  int mode_ext;        /* mp3 frame type                                 */\n  int framesize;       /* number of samples per mp3 frame                */\n\n  /* this data is only computed if mpglib detects a Xing VBR header */\n  unsigned long nsamp; /* number of samples in mp3 file.                 */\n  int totalframes;     /* total number of frames in mp3 file             */\n\n  /* this data is not currently computed by the mpglib routines */\n  int framenum;        /* frames decoded counter                         */\n} mp3data_struct;\n\n/* required call to initialize decoder */\nhip_t CDECL hip_decode_init(void);\n\n/* cleanup call to exit decoder  */\nint CDECL hip_decode_exit(hip_t gfp);\n\n/* HIP reporting functions */\nvoid CDECL hip_set_errorf(hip_t gfp, lame_report_function f);\nvoid CDECL hip_set_debugf(hip_t gfp, lame_report_function f);\nvoid CDECL hip_set_msgf  (hip_t gfp, lame_report_function f);\n\n/*********************************************************************\n * input 1 mp3 frame, output (maybe) pcm data.\n *\n *  nout = hip_decode(hip, mp3buf,len,pcm_l,pcm_r);\n *\n * input:\n *    len          :  number of bytes of mp3 data in mp3buf\n *    mp3buf[len]  :  mp3 data to be decoded\n *\n * output:\n *    nout:  -1    : decoding error\n *            0    : need more data before we can complete the decode\n *           >0    : returned 'nout' samples worth of data in pcm_l,pcm_r\n *    pcm_l[nout]  : left channel data\n *    pcm_r[nout]  : right channel data\n *\n *********************************************************************/\nint CDECL hip_decode( hip_t           gfp\n                    , unsigned char * mp3buf\n                    , size_t          len\n                    , short           pcm_l[]\n                    , short           pcm_r[]\n                    );\n\n/* same as hip_decode, and also returns mp3 header data */\nint CDECL hip_decode_headers( hip_t           gfp\n                            , unsigned char*  mp3buf\n                            , size_t          len\n                            , short           pcm_l[]\n                            , short           pcm_r[]\n                            , mp3data_struct* mp3data\n                            );\n\n/* same as hip_decode, but returns at most one frame */\nint CDECL hip_decode1( hip_t          gfp\n                     , unsigned char* mp3buf\n                     , size_t         len\n                     , short          pcm_l[]\n                     , short          pcm_r[]\n                     );\n\n/* same as hip_decode1, but returns at most one frame and mp3 header data */\nint CDECL hip_decode1_headers( hip_t           gfp\n                             , unsigned char*  mp3buf\n                             , size_t          len\n                             , short           pcm_l[]\n                             , short           pcm_r[]\n                             , mp3data_struct* mp3data\n                             );\n\n/* same as hip_decode1_headers, but also returns enc_delay and enc_padding\n   from VBR Info tag, (-1 if no info tag was found) */\nint CDECL hip_decode1_headersB( hip_t gfp\n                              , unsigned char*   mp3buf\n                              , size_t           len\n                              , short            pcm_l[]\n                              , short            pcm_r[]\n                              , mp3data_struct*  mp3data\n                              , int             *enc_delay\n                              , int             *enc_padding\n                              );\n\n\n\n/* OBSOLETE:\n * lame_decode... functions are there to keep old code working\n * but it is strongly recommended to replace calls by hip_decode...\n * function calls, see above.\n */\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n#else\nint CDECL lame_decode_init(void);\nint CDECL lame_decode(\n        unsigned char *  mp3buf,\n        int              len,\n        short            pcm_l[],\n        short            pcm_r[] );\nint CDECL lame_decode_headers(\n        unsigned char*   mp3buf,\n        int              len,\n        short            pcm_l[],\n        short            pcm_r[],\n        mp3data_struct*  mp3data );\nint CDECL lame_decode1(\n        unsigned char*  mp3buf,\n        int             len,\n        short           pcm_l[],\n        short           pcm_r[] );\nint CDECL lame_decode1_headers(\n        unsigned char*   mp3buf,\n        int              len,\n        short            pcm_l[],\n        short            pcm_r[],\n        mp3data_struct*  mp3data );\nint CDECL lame_decode1_headersB(\n        unsigned char*   mp3buf,\n        int              len,\n        short            pcm_l[],\n        short            pcm_r[],\n        mp3data_struct*  mp3data,\n        int              *enc_delay,\n        int              *enc_padding );\nint CDECL lame_decode_exit(void);\n\n#endif /* obsolete lame_decode API calls */\n\n\n/*********************************************************************\n *\n * id3tag stuff\n *\n *********************************************************************/\n\n/*\n * id3tag.h -- Interface to write ID3 version 1 and 2 tags.\n *\n * Copyright (C) 2000 Don Melton.\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\n\n/* utility to obtain alphabetically sorted list of genre names with numbers */\nvoid CDECL id3tag_genre_list(\n        void (*handler)(int, const char *, void *),\n        void*  cookie);\n\nvoid CDECL id3tag_init     (lame_t gfp);\n\n/* force addition of version 2 tag */\nvoid CDECL id3tag_add_v2   (lame_t gfp);\n\n/* add only a version 1 tag */\nvoid CDECL id3tag_v1_only  (lame_t gfp);\n\n/* add only a version 2 tag */\nvoid CDECL id3tag_v2_only  (lame_t gfp);\n\n/* pad version 1 tag with spaces instead of nulls */\nvoid CDECL id3tag_space_v1 (lame_t gfp);\n\n/* pad version 2 tag with extra 128 bytes */\nvoid CDECL id3tag_pad_v2   (lame_t gfp);\n\n/* pad version 2 tag with extra n bytes */\nvoid CDECL id3tag_set_pad  (lame_t gfp, size_t n);\n\nvoid CDECL id3tag_set_title(lame_t gfp, const char* title);\nvoid CDECL id3tag_set_artist(lame_t gfp, const char* artist);\nvoid CDECL id3tag_set_album(lame_t gfp, const char* album);\nvoid CDECL id3tag_set_year(lame_t gfp, const char* year);\nvoid CDECL id3tag_set_comment(lame_t gfp, const char* comment);\n            \n/* return -1 result if track number is out of ID3v1 range\n                    and ignored for ID3v1 */\nint CDECL id3tag_set_track(lame_t gfp, const char* track);\n\n/* return non-zero result if genre name or number is invalid\n  result 0: OK\n  result -1: genre number out of range\n  result -2: no valid ID3v1 genre name, mapped to ID3v1 'Other'\n             but taken as-is for ID3v2 genre tag */\nint CDECL id3tag_set_genre(lame_t gfp, const char* genre);\n\n/* return non-zero result if field name is invalid */\nint CDECL id3tag_set_fieldvalue(lame_t gfp, const char* fieldvalue);\n\n/* return non-zero result if image type is invalid */\nint CDECL id3tag_set_albumart(lame_t gfp, const char* image, size_t size);\n\n/* lame_get_id3v1_tag copies ID3v1 tag into buffer.\n * Function returns number of bytes copied into buffer, or number\n * of bytes rquired if buffer 'size' is too small.\n * Function fails, if returned value is larger than 'size'.\n * NOTE:\n * This functions does nothing, if user/LAME disabled ID3v1 tag.\n */\nsize_t CDECL lame_get_id3v1_tag(lame_t gfp, unsigned char* buffer, size_t size);\n\n/* lame_get_id3v2_tag copies ID3v2 tag into buffer.\n * Function returns number of bytes copied into buffer, or number\n * of bytes rquired if buffer 'size' is too small.\n * Function fails, if returned value is larger than 'size'.\n * NOTE:\n * This functions does nothing, if user/LAME disabled ID3v2 tag.\n */\nsize_t CDECL lame_get_id3v2_tag(lame_t gfp, unsigned char* buffer, size_t size);\n\n/* normaly lame_init_param writes ID3v2 tags into the audio stream\n * Call lame_set_write_id3tag_automatic(gfp, 0) before lame_init_param\n * to turn off this behaviour and get ID3v2 tag with above function\n * write it yourself into your file.\n */\nvoid CDECL lame_set_write_id3tag_automatic(lame_global_flags * gfp, int);\nint CDECL lame_get_write_id3tag_automatic(lame_global_flags const* gfp);\n\n/* experimental */\nint CDECL id3tag_set_textinfo_latin1(lame_t gfp, char const *id, char const *text);\n\n/* experimental */\nint CDECL id3tag_set_comment_latin1(lame_t gfp, char const *lang, char const *desc, char const *text);\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n#else\n/* experimental */\nint CDECL id3tag_set_textinfo_ucs2(lame_t gfp, char const *id, unsigned short const *text);\n\n/* experimental */\nint CDECL id3tag_set_comment_ucs2(lame_t gfp, char const *lang,\n                                  unsigned short const *desc, unsigned short const *text);\n\n/* experimental */\nint CDECL id3tag_set_fieldvalue_ucs2(lame_t gfp, const unsigned short *fieldvalue);\n#endif\n\n/* experimental */\nint CDECL id3tag_set_fieldvalue_utf16(lame_t gfp, const unsigned short *fieldvalue);\n\n/* experimental */\nint CDECL id3tag_set_textinfo_utf16(lame_t gfp, char const *id, unsigned short const *text);\n\n/* experimental */\nint CDECL id3tag_set_comment_utf16(lame_t gfp, char const *lang, unsigned short const *desc, unsigned short const *text);\n\n\n/***********************************************************************\n*\n*  list of valid bitrates [kbps] & sample frequencies [Hz].\n*  first index: 0: MPEG-2   values  (sample frequencies 16...24 kHz)\n*               1: MPEG-1   values  (sample frequencies 32...48 kHz)\n*               2: MPEG-2.5 values  (sample frequencies  8...12 kHz)\n***********************************************************************/\n\nextern const int     bitrate_table    [3][16];\nextern const int     samplerate_table [3][ 4];\n\n/* access functions for use in DLL, global vars are not exported */\nint CDECL lame_get_bitrate(int mpeg_version, int table_index);\nint CDECL lame_get_samplerate(int mpeg_version, int table_index);\n\n\n/* maximum size of albumart image (128KB), which affects LAME_MAXMP3BUFFER\n   as well since lame_encode_buffer() also returns ID3v2 tag data */\n#define LAME_MAXALBUMART    (128 * 1024)\n\n/* maximum size of mp3buffer needed if you encode at most 1152 samples for\n   each call to lame_encode_buffer.  see lame_encode_buffer() below  \n   (LAME_MAXMP3BUFFER is now obsolete)  */\n#define LAME_MAXMP3BUFFER   (16384 + LAME_MAXALBUMART)\n\n\ntypedef enum {\n    LAME_OKAY             =   0,\n    LAME_NOERROR          =   0,\n    LAME_GENERICERROR     =  -1,\n    LAME_NOMEM            = -10,\n    LAME_BADBITRATE       = -11,\n    LAME_BADSAMPFREQ      = -12,\n    LAME_INTERNALERROR    = -13,\n\n    FRONTEND_READERROR    = -80,\n    FRONTEND_WRITEERROR   = -81,\n    FRONTEND_FILETOOLARGE = -82\n\n} lame_errorcodes_t;\n\n#ifdef __cplusplus\n}\n#endif\n//#if defined(__cplusplus)\n//}\n//#endif\n#endif /* LAME_LAME_H */\n\n"
  },
  {
    "path": "app/jni/include/silk.h",
    "content": "//\n// Created by ketian on 16-9-23.\n//\n\n#ifndef JNI_SILK_H\n#define JNI_SILK_H\n\n#include <android/log.h>\n#include <stdio.h>\n\nint convertSilk2PCM(const char *src, const FILE *dest);\n\n#define LOG_TAG \"tian.ke\"\n#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)\n#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)\n\n#endif //JNI_SILK_H\n"
  },
  {
    "path": "app/jni/libmp3lame/VbrTag.c",
    "content": "/*\n *      Xing VBR tagging for LAME.\n *\n *      Copyright (c) 1999 A.L. Faber\n *      Copyright (c) 2001 Jonathan Dee\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: VbrTag.c,v 1.103.2.1 2011/11/18 09:18:28 robert Exp $ */\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include <malloc.h>\n#include <string.h>\n//#include <__clang_cuda_math_forward_declares.h>\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"bitstream.h\"\n#include \"VbrTag.h\"\n#include \"lame_global_flags.h\"\n#include \"tables.h\"\n\n#ifdef __sun__\n/* woraround for SunOS 4.x, it has SEEK_* defined here */\n#include <unistd.h>\n#endif\n\n\n#ifdef _DEBUG\n/*  #define DEBUG_VBRTAG */\n#endif\n\n/*\n *    4 bytes for Header Tag\n *    4 bytes for Header Flags\n *  100 bytes for entry (NUMTOCENTRIES)\n *    4 bytes for FRAME SIZE\n *    4 bytes for STREAM_SIZE\n *    4 bytes for VBR SCALE. a VBR quality indicator: 0=best 100=worst\n *   20 bytes for LAME tag.  for example, \"LAME3.12 (beta 6)\"\n * ___________\n *  140 bytes\n*/\n#define VBRHEADERSIZE (NUMTOCENTRIES+4+4+4+4+4)\n\n#define LAMEHEADERSIZE (VBRHEADERSIZE + 9 + 1 + 1 + 8 + 1 + 1 + 3 + 1 + 1 + 2 + 4 + 2 + 2)\n\n/* the size of the Xing header (MPEG1 and MPEG2) in kbps */\n#define XING_BITRATE1 128\n#define XING_BITRATE2  64\n#define XING_BITRATE25 32\n\nextern const char* get_lame_tag_encoder_short_version(void);\n\nstatic const char VBRTag0[] = { \"Xing\" };\nstatic const char VBRTag1[] = { \"Info\" };\n\n\n\n\n/* Lookup table for fast CRC computation\n * See 'CRC_update_lookup'\n * Uses the polynomial x^16+x^15+x^2+1 */\n\nstatic const unsigned int crc16_lookup[256] = {\n    0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,\n    0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,\n    0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,\n    0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,\n    0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,\n    0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,\n    0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,\n    0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,\n    0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,\n    0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,\n    0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,\n    0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,\n    0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,\n    0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,\n    0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,\n    0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,\n    0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,\n    0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,\n    0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,\n    0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,\n    0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,\n    0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,\n    0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,\n    0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,\n    0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,\n    0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,\n    0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,\n    0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,\n    0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,\n    0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,\n    0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,\n    0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040\n};\n\n\n\n\n\n/***********************************************************************\n *  Robert Hegemann 2001-01-17\n ***********************************************************************/\n\nstatic void\naddVbr(VBR_seek_info_t * v, int bitrate)\n{\n    int     i;\n\n    v->nVbrNumFrames++;\n    v->sum += bitrate;\n    v->seen++;\n\n    if (v->seen < v->want) {\n        return;\n    }\n\n    if (v->pos < v->size) {\n        v->bag[v->pos] = v->sum;\n        v->pos++;\n        v->seen = 0;\n    }\n    if (v->pos == v->size) {\n        for (i = 1; i < v->size; i += 2) {\n            v->bag[i / 2] = v->bag[i];\n        }\n        v->want *= 2;\n        v->pos /= 2;\n    }\n}\n\nstatic void\nXing_seek_table(VBR_seek_info_t const* v, unsigned char *t)\n{\n    int     i, indx;\n    int     seek_point;\n\n    if (v->pos <= 0)\n        return;\n\n    for (i = 1; i < NUMTOCENTRIES; ++i) {\n        float   j = i / (float) NUMTOCENTRIES, act, sum;\n        indx = (int) (floor(j * v->pos));\n        if (indx > v->pos - 1)\n            indx = v->pos - 1;\n        act = v->bag[indx];\n        sum = v->sum;\n        seek_point = (int) (256. * act / sum);\n        if (seek_point > 255)\n            seek_point = 255;\n        t[i] = seek_point;\n    }\n}\n\n#ifdef DEBUG_VBR_SEEKING_TABLE\nstatic void\nprint_seeking(unsigned char *t)\n{\n    int     i;\n\n    printf(\"seeking table \");\n    for (i = 0; i < NUMTOCENTRIES; ++i) {\n        printf(\" %d \", t[i]);\n    }\n    printf(\"\\n\");\n}\n#endif\n\n\n/****************************************************************************\n * AddVbrFrame: Add VBR entry, used to fill the VBR the TOC entries\n * Paramters:\n *      nStreamPos: how many bytes did we write to the bitstream so far\n *                              (in Bytes NOT Bits)\n ****************************************************************************\n*/\nvoid\nAddVbrFrame(lame_internal_flags * gfc)\n{\n    int     kbps = bitrate_table[gfc->cfg.version][gfc->ov_enc.bitrate_index];\n    assert(gfc->VBR_seek_table.bag);\n    addVbr(&gfc->VBR_seek_table, kbps);\n}\n\n\n/*-------------------------------------------------------------*/\nstatic int\nExtractI4(const unsigned char *buf)\n{\n    int     x;\n    /* big endian extract */\n    x = buf[0];\n    x <<= 8;\n    x |= buf[1];\n    x <<= 8;\n    x |= buf[2];\n    x <<= 8;\n    x |= buf[3];\n    return x;\n}\n\nstatic void\nCreateI4(unsigned char *buf, uint32_t nValue)\n{\n    /* big endian create */\n    buf[0] = (nValue >> 24) & 0xff;\n    buf[1] = (nValue >> 16) & 0xff;\n    buf[2] = (nValue >> 8) & 0xff;\n    buf[3] = (nValue) & 0xff;\n}\n\n\n\nstatic void\nCreateI2(unsigned char *buf, int nValue)\n{\n    /* big endian create */\n    buf[0] = (nValue >> 8) & 0xff;\n    buf[1] = (nValue) & 0xff;\n}\n\n/* check for magic strings*/\nstatic int\nIsVbrTag(const unsigned char *buf)\n{\n    int     isTag0, isTag1;\n\n    isTag0 = ((buf[0] == VBRTag0[0]) && (buf[1] == VBRTag0[1]) && (buf[2] == VBRTag0[2])\n              && (buf[3] == VBRTag0[3]));\n    isTag1 = ((buf[0] == VBRTag1[0]) && (buf[1] == VBRTag1[1]) && (buf[2] == VBRTag1[2])\n              && (buf[3] == VBRTag1[3]));\n\n    return (isTag0 || isTag1);\n}\n\n#define SHIFT_IN_BITS_VALUE(x,n,v) ( x = (x << (n)) | ( (v) & ~(-1u << (n)) ) )\n\nstatic void\nsetLameTagFrameHeader(lame_internal_flags const *gfc, unsigned char *buffer)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncResult_t const *const eov = &gfc->ov_enc;\n    char    abyte, bbyte;\n\n    SHIFT_IN_BITS_VALUE(buffer[0], 8u, 0xffu);\n\n    SHIFT_IN_BITS_VALUE(buffer[1], 3u, 7);\n    SHIFT_IN_BITS_VALUE(buffer[1], 1u, (cfg->samplerate_out < 16000) ? 0 : 1);\n    SHIFT_IN_BITS_VALUE(buffer[1], 1u, cfg->version);\n    SHIFT_IN_BITS_VALUE(buffer[1], 2u, 4 - 3);\n    SHIFT_IN_BITS_VALUE(buffer[1], 1u, (!cfg->error_protection) ? 1 : 0);\n\n    SHIFT_IN_BITS_VALUE(buffer[2], 4u, eov->bitrate_index);\n    SHIFT_IN_BITS_VALUE(buffer[2], 2u, cfg->samplerate_index);\n    SHIFT_IN_BITS_VALUE(buffer[2], 1u, 0);\n    SHIFT_IN_BITS_VALUE(buffer[2], 1u, cfg->extension);\n\n    SHIFT_IN_BITS_VALUE(buffer[3], 2u, cfg->mode);\n    SHIFT_IN_BITS_VALUE(buffer[3], 2u, eov->mode_ext);\n    SHIFT_IN_BITS_VALUE(buffer[3], 1u, cfg->copyright);\n    SHIFT_IN_BITS_VALUE(buffer[3], 1u, cfg->original);\n    SHIFT_IN_BITS_VALUE(buffer[3], 2u, cfg->emphasis);\n\n    /* the default VBR header. 48 kbps layer III, no padding, no crc */\n    /* but sampling freq, mode andy copyright/copy protection taken */\n    /* from first valid frame */\n    buffer[0] = (uint8_t) 0xff;\n    abyte = (buffer[1] & (unsigned char) 0xf1);\n    {\n        int     bitrate;\n        if (1 == cfg->version) {\n            bitrate = XING_BITRATE1;\n        }\n        else {\n            if (cfg->samplerate_out < 16000)\n                bitrate = XING_BITRATE25;\n            else\n                bitrate = XING_BITRATE2;\n        }\n\n        if (cfg->vbr == vbr_off)\n            bitrate = cfg->avg_bitrate;\n\n        if (cfg->free_format)\n            bbyte = 0x00;\n        else\n            bbyte = 16 * BitrateIndex(bitrate, cfg->version, cfg->samplerate_out);\n    }\n\n    /* Use as much of the info from the real frames in the\n     * Xing header:  samplerate, channels, crc, etc...\n     */\n    if (cfg->version == 1) {\n        /* MPEG1 */\n        buffer[1] = abyte | (char) 0x0a; /* was 0x0b; */\n        abyte = buffer[2] & (char) 0x0d; /* AF keep also private bit */\n        buffer[2] = (char) bbyte | abyte; /* 64kbs MPEG1 frame */\n    }\n    else {\n        /* MPEG2 */\n        buffer[1] = abyte | (char) 0x02; /* was 0x03; */\n        abyte = buffer[2] & (char) 0x0d; /* AF keep also private bit */\n        buffer[2] = (char) bbyte | abyte; /* 64kbs MPEG2 frame */\n    }\n}\n\n#if 0\nstatic int CheckVbrTag(unsigned char *buf);\n\n/*-------------------------------------------------------------*/\n/* Same as GetVbrTag below, but only checks for the Xing tag.\n   requires buf to contain only 40 bytes */\n/*-------------------------------------------------------------*/\nint\nCheckVbrTag(unsigned char *buf)\n{\n    int     h_id, h_mode;\n\n    /* get selected MPEG header data */\n    h_id = (buf[1] >> 3) & 1;\n    h_mode = (buf[3] >> 6) & 3;\n\n    /*  determine offset of header */\n    if (h_id) {\n        /* mpeg1 */\n        if (h_mode != 3)\n            buf += (32 + 4);\n        else\n            buf += (17 + 4);\n    }\n    else {\n        /* mpeg2 */\n        if (h_mode != 3)\n            buf += (17 + 4);\n        else\n            buf += (9 + 4);\n    }\n\n    return IsVbrTag(buf);\n}\n#endif\n\nint\nGetVbrTag(VBRTAGDATA * pTagData, const unsigned char *buf)\n{\n    int     i, head_flags;\n    int     h_bitrate, h_id, h_mode, h_sr_index, h_layer;\n    int     enc_delay, enc_padding;\n\n    /* get Vbr header data */\n    pTagData->flags = 0;\n\n    /* get selected MPEG header data */\n    h_layer = (buf[1] >> 1) & 3;\n    if ( h_layer != 0x01 ) {\n        /* the following code assumes Layer-3, so give up here */\n        return 0;\n    }\n    h_id = (buf[1] >> 3) & 1;\n    h_sr_index = (buf[2] >> 2) & 3;\n    h_mode = (buf[3] >> 6) & 3;\n    h_bitrate = ((buf[2] >> 4) & 0xf);\n    h_bitrate = bitrate_table[h_id][h_bitrate];\n\n    /* check for FFE syncword */\n    if ((buf[1] >> 4) == 0xE)\n        pTagData->samprate = samplerate_table[2][h_sr_index];\n    else\n        pTagData->samprate = samplerate_table[h_id][h_sr_index];\n    /* if( h_id == 0 ) */\n    /*  pTagData->samprate >>= 1; */\n\n\n\n    /*  determine offset of header */\n    if (h_id) {\n        /* mpeg1 */\n        if (h_mode != 3)\n            buf += (32 + 4);\n        else\n            buf += (17 + 4);\n    }\n    else {\n        /* mpeg2 */\n        if (h_mode != 3)\n            buf += (17 + 4);\n        else\n            buf += (9 + 4);\n    }\n\n    if (!IsVbrTag(buf))\n        return 0;\n\n    buf += 4;\n\n    pTagData->h_id = h_id;\n\n    head_flags = pTagData->flags = ExtractI4(buf);\n    buf += 4;           /* get flags */\n\n    if (head_flags & FRAMES_FLAG) {\n        pTagData->frames = ExtractI4(buf);\n        buf += 4;\n    }\n\n    if (head_flags & BYTES_FLAG) {\n        pTagData->bytes = ExtractI4(buf);\n        buf += 4;\n    }\n\n    if (head_flags & TOC_FLAG) {\n        if (&(pTagData->toc) != NULL) { //todo 不确定是否解决\n            for (i = 0; i < NUMTOCENTRIES; i++)\n                pTagData->toc[i] = buf[i];\n        }\n        buf += NUMTOCENTRIES;\n    }\n\n    pTagData->vbr_scale = -1;\n\n    if (head_flags & VBR_SCALE_FLAG) {\n        pTagData->vbr_scale = ExtractI4(buf);\n        buf += 4;\n    }\n\n    pTagData->headersize = ((h_id + 1) * 72000 * h_bitrate) / pTagData->samprate;\n\n    buf += 21;\n    enc_delay = buf[0] << 4;\n    enc_delay += buf[1] >> 4;\n    enc_padding = (buf[1] & 0x0F) << 8;\n    enc_padding += buf[2];\n    /* check for reasonable values (this may be an old Xing header, */\n    /* not a INFO tag) */\n    if (enc_delay < 0 || enc_delay > 3000)\n        enc_delay = -1;\n    if (enc_padding < 0 || enc_padding > 3000)\n        enc_padding = -1;\n\n    pTagData->enc_delay = enc_delay;\n    pTagData->enc_padding = enc_padding;\n\n#ifdef DEBUG_VBRTAG\n    fprintf(stderr, \"\\n\\n********************* VBR TAG INFO *****************\\n\");\n    fprintf(stderr, \"tag         :%s\\n\", VBRTag);\n    fprintf(stderr, \"head_flags  :%d\\n\", head_flags);\n    fprintf(stderr, \"bytes       :%d\\n\", pTagData->bytes);\n    fprintf(stderr, \"frames      :%d\\n\", pTagData->frames);\n    fprintf(stderr, \"VBR Scale   :%d\\n\", pTagData->vbr_scale);\n    fprintf(stderr, \"enc_delay  = %i \\n\", enc_delay);\n    fprintf(stderr, \"enc_padding= %i \\n\", enc_padding);\n    fprintf(stderr, \"toc:\\n\");\n    if (pTagData->toc != NULL) {\n        for (i = 0; i < NUMTOCENTRIES; i++) {\n            if ((i % 10) == 0)\n                fprintf(stderr, \"\\n\");\n            fprintf(stderr, \" %3d\", (int) (pTagData->toc[i]));\n        }\n    }\n    fprintf(stderr, \"\\n***************** END OF VBR TAG INFO ***************\\n\");\n#endif\n    return 1;           /* success */\n}\n\n\n/****************************************************************************\n * InitVbrTag: Initializes the header, and write empty frame to stream\n * Paramters:\n *                              fpStream: pointer to output file stream\n *                              nMode   : Channel Mode: 0=STEREO 1=JS 2=DS 3=MONO\n ****************************************************************************\n*/\nint\nInitVbrTag(lame_global_flags * gfp)\n{\n    lame_internal_flags *gfc = gfp->internal_flags;\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     kbps_header;\n\n#define MAXFRAMESIZE 2880 /* or 0xB40, the max freeformat 640 32kHz framesize */\n\n    /*\n     * Xing VBR pretends to be a 48kbs layer III frame.  (at 44.1kHz).\n     * (at 48kHz they use 56kbs since 48kbs frame not big enough for\n     * table of contents)\n     * let's always embed Xing header inside a 64kbs layer III frame.\n     * this gives us enough room for a LAME version string too.\n     * size determined by sampling frequency (MPEG1)\n     * 32kHz:    216 bytes@48kbs    288bytes@ 64kbs\n     * 44.1kHz:  156 bytes          208bytes@64kbs     (+1 if padding = 1)\n     * 48kHz:    144 bytes          192\n     *\n     * MPEG 2 values are the same since the framesize and samplerate\n     * are each reduced by a factor of 2.\n     */\n\n\n    if (1 == cfg->version) {\n        kbps_header = XING_BITRATE1;\n    }\n    else {\n        if (cfg->samplerate_out < 16000)\n            kbps_header = XING_BITRATE25;\n        else\n            kbps_header = XING_BITRATE2;\n    }\n\n    if (cfg->vbr == vbr_off)\n        kbps_header = cfg->avg_bitrate;\n\n    /** make sure LAME Header fits into Frame\n     */\n    {\n        int     total_frame_size = ((cfg->version + 1) * 72000 * kbps_header) / cfg->samplerate_out;\n        int     header_size = (cfg->sideinfo_len + LAMEHEADERSIZE);\n        gfc->VBR_seek_table.TotalFrameSize = total_frame_size;\n        if (total_frame_size < header_size || total_frame_size > MAXFRAMESIZE) {\n            /* disable tag, it wont fit */\n            gfc->cfg.write_lame_tag = 0;\n            return 0;\n        }\n    }\n\n    gfc->VBR_seek_table.nVbrNumFrames = 0;\n    gfc->VBR_seek_table.nBytesWritten = 0;\n    gfc->VBR_seek_table.sum = 0;\n\n    gfc->VBR_seek_table.seen = 0;\n    gfc->VBR_seek_table.want = 1;\n    gfc->VBR_seek_table.pos = 0;\n\n    if (gfc->VBR_seek_table.bag == NULL) {\n        gfc->VBR_seek_table.bag = malloc(400 * sizeof(int));\n        if (gfc->VBR_seek_table.bag != NULL) {\n            gfc->VBR_seek_table.size = 400;\n        }\n        else {\n            gfc->VBR_seek_table.size = 0;\n            ERRORF(gfc, \"Error: can't allocate VbrFrames buffer\\n\");\n            gfc->cfg.write_lame_tag = 0;\n            return -1;\n        }\n    }\n\n    /* write dummy VBR tag of all 0's into bitstream */\n    {\n        uint8_t buffer[MAXFRAMESIZE];\n        size_t  i, n;\n\n        memset(buffer, 0, sizeof(buffer));\n        setLameTagFrameHeader(gfc, buffer);\n        n = gfc->VBR_seek_table.TotalFrameSize;\n        for (i = 0; i < n; ++i) {\n            add_dummy_byte(gfc, buffer[i], 1);\n        }\n    }\n    /* Success */\n    return 0;\n}\n\n\n\n/* fast CRC-16 computation - uses table crc16_lookup 8*/\nstatic uint16_t\nCRC_update_lookup(uint16_t value, uint16_t crc)\n{\n    uint16_t tmp;\n    tmp = crc ^ value;\n    crc = (crc >> 8) ^ crc16_lookup[tmp & 0xff];\n    return crc;\n}\n\nvoid\nUpdateMusicCRC(uint16_t * crc, unsigned char const *buffer, int size)\n{\n    int     i;\n    for (i = 0; i < size; ++i)\n        *crc = CRC_update_lookup(buffer[i], *crc);\n}\n\n\n\n\n\n/****************************************************************************\n * Jonathan Dee 2001/08/31\n *\n * PutLameVBR: Write LAME info: mini version + info on various switches used\n * Paramters:\n *                              pbtStreamBuffer : pointer to output buffer\n *                              id3v2size               : size of id3v2 tag in bytes\n *                              crc                             : computation of crc-16 of Lame Tag so far (starting at frame sync)\n *\n ****************************************************************************\n*/\nstatic int\nPutLameVBR(lame_global_flags const *gfp, size_t nMusicLength, uint8_t * pbtStreamBuffer, uint16_t crc)\n{\n    lame_internal_flags const *gfc = gfp->internal_flags;\n    SessionConfig_t const *const cfg = &gfc->cfg;\n\n    int     nBytesWritten = 0;\n    int     i;\n\n    int     enc_delay = gfc->ov_enc.encoder_delay; /* encoder delay */\n    int     enc_padding = gfc->ov_enc.encoder_padding; /* encoder padding  */\n\n    /*recall: cfg->vbr_q is for example set by the switch -V  */\n    /*   gfp->quality by -q, -h, -f, etc */\n\n    int     nQuality = (100 - 10 * gfp->VBR_q - gfp->quality);\n\n\n    /*\n    NOTE:\n            Even though the specification for the LAME VBR tag\n            did explicitly mention other encoders than LAME,\n            many SW/HW decoder seem to be able to make use of\n            this tag only, if the encoder version starts with LAME.\n            To be compatible with such decoders, ANY encoder will\n            be forced to write a fake LAME version string!\n            As a result, the encoder version info becomes worthless.\n    */\n    const char *szVersion = get_lame_tag_encoder_short_version();\n    uint8_t nVBR;\n    uint8_t nRevision = 0x00;\n    uint8_t nRevMethod;\n    uint8_t vbr_type_translator[] = { 1, 5, 3, 2, 4, 0, 3 }; /*numbering different in vbr_mode vs. Lame tag */\n\n    uint8_t nLowpass =\n        (((cfg->lowpassfreq / 100.0) + .5) > 255 ? 255 : (cfg->lowpassfreq / 100.0) + .5);\n\n    uint32_t nPeakSignalAmplitude = 0;\n\n    uint16_t nRadioReplayGain = 0;\n    uint16_t nAudiophileReplayGain = 0;\n\n    uint8_t nNoiseShaping = cfg->noise_shaping;\n    uint8_t nStereoMode = 0;\n    int     bNonOptimal = 0;\n    uint8_t nSourceFreq = 0;\n    uint8_t nMisc = 0;\n    uint16_t nMusicCRC = 0;\n\n    /*psy model type: Gpsycho or NsPsytune */\n    unsigned char bExpNPsyTune = 1; /* only NsPsytune */\n    unsigned char bSafeJoint = (cfg->use_safe_joint_stereo) != 0;\n\n    unsigned char bNoGapMore = 0;\n    unsigned char bNoGapPrevious = 0;\n\n    int     nNoGapCount = gfp->nogap_total;\n    int     nNoGapCurr = gfp->nogap_current;\n\n\n    uint8_t nAthType = cfg->ATHtype; /*4 bits. */\n\n    uint8_t nFlags = 0;\n\n    /* if ABR, {store bitrate <=255} else { store \"-b\"} */\n    int     nABRBitrate;\n    switch (cfg->vbr) {\n    case vbr_abr:{\n            nABRBitrate = cfg->vbr_avg_bitrate_kbps;\n            break;\n        }\n    case vbr_off:{\n            nABRBitrate = cfg->avg_bitrate;\n            break;\n        }\n    default:{          /*vbr modes */\n            nABRBitrate = bitrate_table[cfg->version][cfg->vbr_min_bitrate_index];;\n        }\n    }\n\n\n    /*revision and vbr method */\n    if (cfg->vbr < sizeof(vbr_type_translator))\n        nVBR = vbr_type_translator[cfg->vbr];\n    else\n        nVBR = 0x00;    /*unknown. */\n\n    nRevMethod = 0x10 * nRevision + nVBR;\n\n\n    /* ReplayGain */\n    if (cfg->findReplayGain) {\n        int     RadioGain = gfc->ov_rpg.RadioGain;\n        if (RadioGain > 0x1FE)\n            RadioGain = 0x1FE;\n        if (RadioGain < -0x1FE)\n            RadioGain = -0x1FE;\n\n        nRadioReplayGain = 0x2000; /* set name code */\n        nRadioReplayGain |= 0xC00; /* set originator code to `determined automatically' */\n\n        if (RadioGain >= 0)\n            nRadioReplayGain |= RadioGain; /* set gain adjustment */\n        else {\n            nRadioReplayGain |= 0x200; /* set the sign bit */\n            nRadioReplayGain |= -RadioGain; /* set gain adjustment */\n        }\n    }\n\n    /* peak sample */\n    if (cfg->findPeakSample)\n        nPeakSignalAmplitude =\n            abs((int) ((((FLOAT) gfc->ov_rpg.PeakSample) / 32767.0) * pow(2, 23) + .5));\n\n    /*nogap */\n    if (nNoGapCount != -1) {\n        if (nNoGapCurr > 0)\n            bNoGapPrevious = 1;\n\n        if (nNoGapCurr < nNoGapCount - 1)\n            bNoGapMore = 1;\n    }\n\n    /*flags */\n\n    nFlags = nAthType + (bExpNPsyTune << 4)\n        + (bSafeJoint << 5)\n        + (bNoGapMore << 6)\n        + (bNoGapPrevious << 7);\n\n\n    if (nQuality < 0)\n        nQuality = 0;\n\n    /*stereo mode field... a bit ugly. */\n\n    switch (cfg->mode) {\n    case MONO:\n        nStereoMode = 0;\n        break;\n    case STEREO:\n        nStereoMode = 1;\n        break;\n    case DUAL_CHANNEL:\n        nStereoMode = 2;\n        break;\n    case JOINT_STEREO:\n        if (cfg->force_ms)\n            nStereoMode = 4;\n        else\n            nStereoMode = 3;\n        break;\n    case NOT_SET:\n        /* FALLTHROUGH */\n    default:\n        nStereoMode = 7;\n        break;\n    }\n\n    /*Intensity stereo : nStereoMode = 6. IS is not implemented */\n\n    if (cfg->samplerate_in <= 32000)\n        nSourceFreq = 0x00;\n    else if (cfg->samplerate_in == 48000)\n        nSourceFreq = 0x02;\n    else if (cfg->samplerate_in > 48000)\n        nSourceFreq = 0x03;\n    else\n        nSourceFreq = 0x01; /*default is 44100Hz. */\n\n\n    /*Check if the user overrided the default LAME behaviour with some nasty options */\n\n    if (cfg->short_blocks == short_block_forced || cfg->short_blocks == short_block_dispensed || ((cfg->lowpassfreq == -1) && (cfg->highpassfreq == -1)) || /* \"-k\" */\n        (cfg->disable_reservoir && cfg->avg_bitrate < 320) ||\n        cfg->noATH || cfg->ATHonly || (nAthType == 0) || cfg->samplerate_in <= 32000)\n        bNonOptimal = 1;\n\n    nMisc = nNoiseShaping + (nStereoMode << 2)\n        + (bNonOptimal << 5)\n        + (nSourceFreq << 6);\n\n\n    nMusicCRC = gfc->nMusicCRC;\n\n\n    /*Write all this information into the stream */\n    CreateI4(&pbtStreamBuffer[nBytesWritten], nQuality);\n    nBytesWritten += 4;\n\n    strncpy((char *) &pbtStreamBuffer[nBytesWritten], szVersion, 9);\n    nBytesWritten += 9;\n\n    pbtStreamBuffer[nBytesWritten] = nRevMethod;\n    nBytesWritten++;\n\n    pbtStreamBuffer[nBytesWritten] = nLowpass;\n    nBytesWritten++;\n\n    CreateI4(&pbtStreamBuffer[nBytesWritten], nPeakSignalAmplitude);\n    nBytesWritten += 4;\n\n    CreateI2(&pbtStreamBuffer[nBytesWritten], nRadioReplayGain);\n    nBytesWritten += 2;\n\n    CreateI2(&pbtStreamBuffer[nBytesWritten], nAudiophileReplayGain);\n    nBytesWritten += 2;\n\n    pbtStreamBuffer[nBytesWritten] = nFlags;\n    nBytesWritten++;\n\n    if (nABRBitrate >= 255)\n        pbtStreamBuffer[nBytesWritten] = 0xFF;\n    else\n        pbtStreamBuffer[nBytesWritten] = nABRBitrate;\n    nBytesWritten++;\n\n    pbtStreamBuffer[nBytesWritten] = enc_delay >> 4; /* works for win32, does it for unix? */\n    pbtStreamBuffer[nBytesWritten + 1] = (enc_delay << 4) + (enc_padding >> 8);\n    pbtStreamBuffer[nBytesWritten + 2] = enc_padding;\n\n    nBytesWritten += 3;\n\n    pbtStreamBuffer[nBytesWritten] = nMisc;\n    nBytesWritten++;\n\n\n    pbtStreamBuffer[nBytesWritten++] = 0; /*unused in rev0 */\n\n    CreateI2(&pbtStreamBuffer[nBytesWritten], cfg->preset);\n    nBytesWritten += 2;\n\n    CreateI4(&pbtStreamBuffer[nBytesWritten], (int) nMusicLength);\n    nBytesWritten += 4;\n\n    CreateI2(&pbtStreamBuffer[nBytesWritten], nMusicCRC);\n    nBytesWritten += 2;\n\n    /*Calculate tag CRC.... must be done here, since it includes\n     *previous information*/\n\n    for (i = 0; i < nBytesWritten; i++)\n        crc = CRC_update_lookup(pbtStreamBuffer[i], crc);\n\n    CreateI2(&pbtStreamBuffer[nBytesWritten], crc);\n    nBytesWritten += 2;\n\n    return nBytesWritten;\n}\n\nstatic long\nskipId3v2(FILE * fpStream)\n{\n    size_t  nbytes;\n    long    id3v2TagSize;\n    unsigned char id3v2Header[10];\n\n    /* seek to the beginning of the stream */\n    if (fseek(fpStream, 0, SEEK_SET) != 0) {\n        return -2;      /* not seekable, abort */\n    }\n    /* read 10 bytes in case there's an ID3 version 2 header here */\n    nbytes = fread(id3v2Header, 1, sizeof(id3v2Header), fpStream);\n    if (nbytes != sizeof(id3v2Header)) {\n        return -3;      /* not readable, maybe opened Write-Only */\n    }\n    /* does the stream begin with the ID3 version 2 file identifier? */\n    if (!strncmp((char *) id3v2Header, \"ID3\", 3)) {\n        /* the tag size (minus the 10-byte header) is encoded into four\n         * bytes where the most significant bit is clear in each byte */\n        id3v2TagSize = (((id3v2Header[6] & 0x7f) << 21)\n                        | ((id3v2Header[7] & 0x7f) << 14)\n                        | ((id3v2Header[8] & 0x7f) << 7)\n                        | (id3v2Header[9] & 0x7f))\n            + sizeof id3v2Header;\n    }\n    else {\n        /* no ID3 version 2 tag in this stream */\n        id3v2TagSize = 0;\n    }\n    return id3v2TagSize;\n}\n\n\n\nsize_t\nlame_get_lametag_frame(lame_global_flags const *gfp, unsigned char *buffer, size_t size)\n{\n    lame_internal_flags *gfc;\n    SessionConfig_t const *cfg;\n    unsigned long stream_size;\n    unsigned int  nStreamIndex;\n    uint8_t btToc[NUMTOCENTRIES];\n\n    if (gfp == 0) {\n        return 0;\n    }\n    gfc = gfp->internal_flags;\n    if (gfc == 0) {\n        return 0;\n    }\n    if (gfc->class_id != LAME_ID) {\n        return 0;\n    }\n    cfg = &gfc->cfg;\n    if (cfg->write_lame_tag == 0) {\n        return 0;\n    }\n    if (gfc->VBR_seek_table.pos <= 0) {\n        return 0;\n    }\n    if (size < gfc->VBR_seek_table.TotalFrameSize) {\n        return gfc->VBR_seek_table.TotalFrameSize;\n    }\n    if (buffer == 0) {\n        return 0;\n    }\n\n    memset(buffer, 0, gfc->VBR_seek_table.TotalFrameSize);\n\n    /* 4 bytes frame header */\n\n    setLameTagFrameHeader(gfc, buffer);\n\n    /* Clear all TOC entries */\n    memset(btToc, 0, sizeof(btToc));\n\n    if (cfg->free_format) {\n        int     i;\n        for (i = 1; i < NUMTOCENTRIES; ++i)\n            btToc[i] = 255 * i / 100;\n    }\n    else {\n        Xing_seek_table(&gfc->VBR_seek_table, btToc);\n    }\n#ifdef DEBUG_VBR_SEEKING_TABLE\n    print_seeking(btToc);\n#endif\n\n    /* Start writing the tag after the zero frame */\n    nStreamIndex = cfg->sideinfo_len;\n    /* note! Xing header specifies that Xing data goes in the\n     * ancillary data with NO ERROR PROTECTION.  If error protecton\n     * in enabled, the Xing data still starts at the same offset,\n     * and now it is in sideinfo data block, and thus will not\n     * decode correctly by non-Xing tag aware players */\n    if (cfg->error_protection)\n        nStreamIndex -= 2;\n\n    /* Put Vbr tag */\n    if (cfg->vbr == vbr_off) {\n        buffer[nStreamIndex++] = VBRTag1[0];\n        buffer[nStreamIndex++] = VBRTag1[1];\n        buffer[nStreamIndex++] = VBRTag1[2];\n        buffer[nStreamIndex++] = VBRTag1[3];\n\n    }\n    else {\n        buffer[nStreamIndex++] = VBRTag0[0];\n        buffer[nStreamIndex++] = VBRTag0[1];\n        buffer[nStreamIndex++] = VBRTag0[2];\n        buffer[nStreamIndex++] = VBRTag0[3];\n    }\n\n    /* Put header flags */\n    CreateI4(&buffer[nStreamIndex], FRAMES_FLAG + BYTES_FLAG + TOC_FLAG + VBR_SCALE_FLAG);\n    nStreamIndex += 4;\n\n    /* Put Total Number of frames */\n    CreateI4(&buffer[nStreamIndex], gfc->VBR_seek_table.nVbrNumFrames);\n    nStreamIndex += 4;\n\n    /* Put total audio stream size, including Xing/LAME Header */\n    stream_size = gfc->VBR_seek_table.nBytesWritten + gfc->VBR_seek_table.TotalFrameSize;\n    CreateI4(&buffer[nStreamIndex], stream_size);\n    nStreamIndex += 4;\n\n    /* Put TOC */\n    memcpy(&buffer[nStreamIndex], btToc, sizeof(btToc));\n    nStreamIndex += sizeof(btToc);\n\n\n    if (cfg->error_protection) {\n        /* (jo) error_protection: add crc16 information to header */\n        CRC_writeheader(gfc, (char *) buffer);\n    }\n    {\n        /*work out CRC so far: initially crc = 0 */\n        uint16_t crc = 0x00;\n        unsigned int i;\n        for (i = 0; i < nStreamIndex; i++)\n            crc = CRC_update_lookup(buffer[i], crc);\n        /*Put LAME VBR info */\n        nStreamIndex += PutLameVBR(gfp, stream_size, buffer + nStreamIndex, crc);\n    }\n\n#ifdef DEBUG_VBRTAG\n    {\n        VBRTAGDATA TestHeader;\n        GetVbrTag(&TestHeader, buffer);\n    }\n#endif\n\n    return gfc->VBR_seek_table.TotalFrameSize;\n}\n\n/***********************************************************************\n *\n * PutVbrTag: Write final VBR tag to the file\n * Paramters:\n *                              lpszFileName: filename of MP3 bit stream\n *                              nVbrScale       : encoder quality indicator (0..100)\n ****************************************************************************\n */\n\nint\nPutVbrTag(lame_global_flags const *gfp, FILE * fpStream)\n{\n    lame_internal_flags *gfc = gfp->internal_flags;\n\n    long    lFileSize;\n    long    id3v2TagSize;\n    size_t  nbytes;\n    uint8_t buffer[MAXFRAMESIZE];\n\n    if (gfc->VBR_seek_table.pos <= 0)\n        return -1;\n\n    /* Seek to end of file */\n    fseek(fpStream, 0, SEEK_END);\n\n    /* Get file size */\n    lFileSize = ftell(fpStream);\n\n    /* Abort if file has zero length. Yes, it can happen :) */\n    if (lFileSize == 0)\n        return -1;\n\n    /*\n     * The VBR tag may NOT be located at the beginning of the stream.\n     * If an ID3 version 2 tag was added, then it must be skipped to write\n     * the VBR tag data.\n     */\n\n    id3v2TagSize = skipId3v2(fpStream);\n\n    if (id3v2TagSize < 0) {\n        return id3v2TagSize;\n    }\n\n    /*Seek to the beginning of the stream */\n    fseek(fpStream, id3v2TagSize, SEEK_SET);\n\n    nbytes = lame_get_lametag_frame(gfp, buffer, sizeof(buffer));\n    if (nbytes > sizeof(buffer)) {\n        return -1;\n    }\n\n    if (nbytes < 1) {\n        return 0;\n    }\n\n    /* Put it all to disk again */\n    if (fwrite(buffer, nbytes, 1, fpStream) != 1) {\n        return -1;\n    }\n\n    return 0;           /* success */\n}\n"
  },
  {
    "path": "app/jni/libmp3lame/VbrTag.h",
    "content": "/*\n *      Xing VBR tagging for LAME.\n *\n *      Copyright (c) 1999 A.L. Faber\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_VRBTAG_H\n#define LAME_VRBTAG_H\n\n\n/* -----------------------------------------------------------\n * A Vbr header may be present in the ancillary\n * data field of the first frame of an mp3 bitstream\n * The Vbr header (optionally) contains\n *      frames      total number of audio frames in the bitstream\n *      bytes       total number of bytes in the bitstream\n *      toc         table of contents\n\n * toc (table of contents) gives seek points\n * for random access\n * the ith entry determines the seek point for\n * i-percent duration\n * seek point in bytes = (toc[i]/256.0) * total_bitstream_bytes\n * e.g. half duration seek point = (toc[50]/256.0) * total_bitstream_bytes\n */\n\n\n#define FRAMES_FLAG     0x0001\n#define BYTES_FLAG      0x0002\n#define TOC_FLAG        0x0004\n#define VBR_SCALE_FLAG  0x0008\n\n#define NUMTOCENTRIES 100\n\n#ifndef lame_internal_flags_defined\n#define lame_internal_flags_defined\nstruct lame_internal_flags;\ntypedef struct lame_internal_flags lame_internal_flags;\n#endif\n\n\n/*structure to receive extracted header */\n/* toc may be NULL*/\ntypedef struct {\n    int     h_id;            /* from MPEG header, 0=MPEG2, 1=MPEG1 */\n    int     samprate;        /* determined from MPEG header */\n    int     flags;           /* from Vbr header data */\n    int     frames;          /* total bit stream frames from Vbr header data */\n    int     bytes;           /* total bit stream bytes from Vbr header data */\n    int     vbr_scale;       /* encoded vbr scale from Vbr header data */\n    unsigned char toc[NUMTOCENTRIES]; /* may be NULL if toc not desired */\n    int     headersize;      /* size of VBR header, in bytes */\n    int     enc_delay;       /* encoder delay */\n    int     enc_padding;     /* encoder paddign added at end of stream */\n} VBRTAGDATA;\n\nint     GetVbrTag(VBRTAGDATA * pTagData, const unsigned char *buf);\n\nint     InitVbrTag(lame_global_flags * gfp);\nint     PutVbrTag(lame_global_flags const *gfp, FILE * fid);\nvoid    AddVbrFrame(lame_internal_flags * gfc);\nvoid    UpdateMusicCRC(uint16_t * crc, const unsigned char *buffer, int size);\n\n#endif\n"
  },
  {
    "path": "app/jni/libmp3lame/bitstream.c",
    "content": "/*\n *      MP3 bitstream Output interface for LAME\n *\n *      Copyright (c) 1999-2000 Mark Taylor\n *      Copyright (c) 1999-2002 Takehiro Tominaga\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\n * $Id: bitstream.c,v 1.97 2011/05/07 16:05:17 rbrito Exp $\n */\n\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <strings.h>\n#include <string.h>\n\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"tables.h\"\n#include \"quantize_pvt.h\"\n#include \"lame_global_flags.h\"\n#include \"gain_analysis.h\"\n#include \"VbrTag.h\"\n#include \"bitstream.h\"\n#include \"tables.h\"\n\n\n\n/* unsigned int is at least this large:  */\n/* we work with ints, so when doing bit manipulation, we limit\n * ourselves to MAX_LENGTH-2 just to be on the safe side */\n#define MAX_LENGTH      32\n\n\n\n#ifdef DEBUG\nstatic int hogege;\n#endif\n\n\n\nstatic int\ncalcFrameLength(SessionConfig_t const *const cfg, int kbps, int pad)\n{\n  return 8 * ((cfg->version + 1) * 72000 * kbps / cfg->samplerate_out + pad);\n}\n\n\n/***********************************************************************\n * compute bitsperframe and mean_bits for a layer III frame\n **********************************************************************/\nint\ngetframebits(const lame_internal_flags * gfc)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncResult_t const *const eov = &gfc->ov_enc;\n    int     bit_rate;\n\n    /* get bitrate in kbps [?] */\n    if (eov->bitrate_index)\n        bit_rate = bitrate_table[cfg->version][eov->bitrate_index];\n    else\n        bit_rate = cfg->avg_bitrate;\n    /*assert(bit_rate <= 550); */\n    assert(8 <= bit_rate && bit_rate <= 640);\n\n    /* main encoding routine toggles padding on and off */\n    /* one Layer3 Slot consists of 8 bits */\n    return calcFrameLength(cfg, bit_rate, eov->padding);\n}\n\nint\nget_max_frame_buffer_size_by_constraint(SessionConfig_t const * cfg, int constraint)\n{\n    int     maxmp3buf = 0;\n    if (cfg->avg_bitrate > 320) {\n        /* in freeformat the buffer is constant */\n        if (constraint == MDB_STRICT_ISO) {\n            maxmp3buf = calcFrameLength(cfg, cfg->avg_bitrate, 0);\n        }\n        else {\n            /* maximum allowed bits per granule are 7680 */\n            maxmp3buf = 7680 * (cfg->version + 1);\n        }\n    }\n    else {\n        int     max_kbps;\n        if (cfg->samplerate_out < 16000) {\n            max_kbps = bitrate_table[cfg->version][8]; /* default: allow 64 kbps (MPEG-2.5) */\n        }\n        else {\n            max_kbps = bitrate_table[cfg->version][14];\n        }\n        switch (constraint) \n        {\n        default:\n        case MDB_DEFAULT:\n            /* Bouvigne suggests this more lax interpretation of the ISO doc instead of using 8*960. */\n            /* All mp3 decoders should have enough buffer to handle this value: size of a 320kbps 32kHz frame */\n            maxmp3buf = 8 * 1440;\n            break;\n        case MDB_STRICT_ISO:\n            maxmp3buf = calcFrameLength(cfg, max_kbps, 0);\n            break;\n        case MDB_MAXIMUM:\n            maxmp3buf = 7680 * (cfg->version + 1);\n            break;\n        }\n    }\n    return maxmp3buf;\n}\n\n\nstatic void\nputheader_bits(lame_internal_flags * gfc)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    Bit_stream_struc *bs = &gfc->bs;\n#ifdef DEBUG\n    hogege += cfg->sideinfo_len * 8;\n#endif\n    memcpy(&bs->buf[bs->buf_byte_idx], esv->header[esv->w_ptr].buf, cfg->sideinfo_len);\n    bs->buf_byte_idx += cfg->sideinfo_len;\n    bs->totbit += cfg->sideinfo_len * 8;\n    esv->w_ptr = (esv->w_ptr + 1) & (MAX_HEADER_BUF - 1);\n}\n\n\n\n\n/*write j bits into the bit stream */\ninline static void\nputbits2(lame_internal_flags * gfc, int val, int j)\n{\n    EncStateVar_t const *const esv = &gfc->sv_enc;\n    Bit_stream_struc *bs;\n    bs = &gfc->bs;\n\n    assert(j < MAX_LENGTH - 2);\n\n    while (j > 0) {\n        int     k;\n        if (bs->buf_bit_idx == 0) {\n            bs->buf_bit_idx = 8;\n            bs->buf_byte_idx++;\n            assert(bs->buf_byte_idx < BUFFER_SIZE);\n            assert(esv->header[esv->w_ptr].write_timing >= bs->totbit);\n            if (esv->header[esv->w_ptr].write_timing == bs->totbit) {\n                putheader_bits(gfc);\n            }\n            bs->buf[bs->buf_byte_idx] = 0;\n        }\n\n        k = Min(j, bs->buf_bit_idx);\n        j -= k;\n\n        bs->buf_bit_idx -= k;\n\n        assert(j < MAX_LENGTH); /* 32 too large on 32 bit machines */\n        assert(bs->buf_bit_idx < MAX_LENGTH);\n\n        bs->buf[bs->buf_byte_idx] |= ((val >> j) << bs->buf_bit_idx);\n        bs->totbit += k;\n    }\n}\n\n/*write j bits into the bit stream, ignoring frame headers */\ninline static void\nputbits_noheaders(lame_internal_flags * gfc, int val, int j)\n{\n    Bit_stream_struc *bs;\n    bs = &gfc->bs;\n\n    assert(j < MAX_LENGTH - 2);\n\n    while (j > 0) {\n        int     k;\n        if (bs->buf_bit_idx == 0) {\n            bs->buf_bit_idx = 8;\n            bs->buf_byte_idx++;\n            assert(bs->buf_byte_idx < BUFFER_SIZE);\n            bs->buf[bs->buf_byte_idx] = 0;\n        }\n\n        k = Min(j, bs->buf_bit_idx);\n        j -= k;\n\n        bs->buf_bit_idx -= k;\n\n        assert(j < MAX_LENGTH); /* 32 too large on 32 bit machines */\n        assert(bs->buf_bit_idx < MAX_LENGTH);\n\n        bs->buf[bs->buf_byte_idx] |= ((val >> j) << bs->buf_bit_idx);\n        bs->totbit += k;\n    }\n}\n\n\n/*\n  Some combinations of bitrate, Fs, and stereo make it impossible to stuff\n  out a frame using just main_data, due to the limited number of bits to\n  indicate main_data_length. In these situations, we put stuffing bits into\n  the ancillary data...\n*/\n\ninline static void\ndrain_into_ancillary(lame_internal_flags * gfc, int remainingBits)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    int     i;\n    assert(remainingBits >= 0);\n\n    if (remainingBits >= 8) {\n        putbits2(gfc, 0x4c, 8);\n        remainingBits -= 8;\n    }\n    if (remainingBits >= 8) {\n        putbits2(gfc, 0x41, 8);\n        remainingBits -= 8;\n    }\n    if (remainingBits >= 8) {\n        putbits2(gfc, 0x4d, 8);\n        remainingBits -= 8;\n    }\n    if (remainingBits >= 8) {\n        putbits2(gfc, 0x45, 8);\n        remainingBits -= 8;\n    }\n\n    if (remainingBits >= 32) {\n        const char *const version = get_lame_short_version();\n        if (remainingBits >= 32)\n            for (i = 0; i < (int) strlen(version) && remainingBits >= 8; ++i) {\n                remainingBits -= 8;\n                putbits2(gfc, version[i], 8);\n            }\n    }\n\n    for (; remainingBits >= 1; remainingBits -= 1) {\n        putbits2(gfc, esv->ancillary_flag, 1);\n        esv->ancillary_flag ^= !cfg->disable_reservoir;\n    }\n\n    assert(remainingBits == 0);\n\n}\n\n/*write N bits into the header */\ninline static void\nwriteheader(lame_internal_flags * gfc, int val, int j)\n{\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    int     ptr = esv->header[esv->h_ptr].ptr;\n\n    while (j > 0) {\n        int const k = Min(j, 8 - (ptr & 7));\n        j -= k;\n        assert(j < MAX_LENGTH); /* >> 32  too large for 32 bit machines */\n        esv->header[esv->h_ptr].buf[ptr >> 3]\n            |= ((val >> j)) << (8 - (ptr & 7) - k);\n        ptr += k;\n    }\n    esv->header[esv->h_ptr].ptr = ptr;\n}\n\n\nstatic int\nCRC_update(int value, int crc)\n{\n    int     i;\n    value <<= 8;\n    for (i = 0; i < 8; i++) {\n        value <<= 1;\n        crc <<= 1;\n\n        if (((crc ^ value) & 0x10000))\n            crc ^= CRC16_POLYNOMIAL;\n    }\n    return crc;\n}\n\n\nvoid\nCRC_writeheader(lame_internal_flags const *gfc, char *header)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     crc = 0xffff;    /* (jo) init crc16 for error_protection */\n    int     i;\n\n    crc = CRC_update(((unsigned char *) header)[2], crc);\n    crc = CRC_update(((unsigned char *) header)[3], crc);\n    for (i = 6; i < cfg->sideinfo_len; i++) {\n        crc = CRC_update(((unsigned char *) header)[i], crc);\n    }\n\n    header[4] = crc >> 8;\n    header[5] = crc & 255;\n}\n\ninline static void\nencodeSideInfo2(lame_internal_flags * gfc, int bitsPerFrame)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncResult_t const *const eov = &gfc->ov_enc;\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    III_side_info_t *l3_side;\n    int     gr, ch;\n\n    l3_side = &gfc->l3_side;\n    esv->header[esv->h_ptr].ptr = 0;\n    memset(esv->header[esv->h_ptr].buf, 0, cfg->sideinfo_len);\n    if (cfg->samplerate_out < 16000)\n        writeheader(gfc, 0xffe, 12);\n    else\n        writeheader(gfc, 0xfff, 12);\n    writeheader(gfc, (cfg->version), 1);\n    writeheader(gfc, 4 - 3, 2);\n    writeheader(gfc, (!cfg->error_protection), 1);\n    writeheader(gfc, (eov->bitrate_index), 4);\n    writeheader(gfc, (cfg->samplerate_index), 2);\n    writeheader(gfc, (eov->padding), 1);\n    writeheader(gfc, (cfg->extension), 1);\n    writeheader(gfc, (cfg->mode), 2);\n    writeheader(gfc, (eov->mode_ext), 2);\n    writeheader(gfc, (cfg->copyright), 1);\n    writeheader(gfc, (cfg->original), 1);\n    writeheader(gfc, (cfg->emphasis), 2);\n    if (cfg->error_protection) {\n        writeheader(gfc, 0, 16); /* dummy */\n    }\n\n    if (cfg->version == 1) {\n        /* MPEG1 */\n        assert(l3_side->main_data_begin >= 0);\n        writeheader(gfc, (l3_side->main_data_begin), 9);\n\n        if (cfg->channels_out == 2)\n            writeheader(gfc, l3_side->private_bits, 3);\n        else\n            writeheader(gfc, l3_side->private_bits, 5);\n\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            int     band;\n            for (band = 0; band < 4; band++) {\n                writeheader(gfc, l3_side->scfsi[ch][band], 1);\n            }\n        }\n\n        for (gr = 0; gr < 2; gr++) {\n            for (ch = 0; ch < cfg->channels_out; ch++) {\n                gr_info *const gi = &l3_side->tt[gr][ch];\n                writeheader(gfc, gi->part2_3_length + gi->part2_length, 12);\n                writeheader(gfc, gi->big_values / 2, 9);\n                writeheader(gfc, gi->global_gain, 8);\n                writeheader(gfc, gi->scalefac_compress, 4);\n\n                if (gi->block_type != NORM_TYPE) {\n                    writeheader(gfc, 1, 1); /* window_switching_flag */\n                    writeheader(gfc, gi->block_type, 2);\n                    writeheader(gfc, gi->mixed_block_flag, 1);\n\n                    if (gi->table_select[0] == 14)\n                        gi->table_select[0] = 16;\n                    writeheader(gfc, gi->table_select[0], 5);\n                    if (gi->table_select[1] == 14)\n                        gi->table_select[1] = 16;\n                    writeheader(gfc, gi->table_select[1], 5);\n\n                    writeheader(gfc, gi->subblock_gain[0], 3);\n                    writeheader(gfc, gi->subblock_gain[1], 3);\n                    writeheader(gfc, gi->subblock_gain[2], 3);\n                }\n                else {\n                    writeheader(gfc, 0, 1); /* window_switching_flag */\n                    if (gi->table_select[0] == 14)\n                        gi->table_select[0] = 16;\n                    writeheader(gfc, gi->table_select[0], 5);\n                    if (gi->table_select[1] == 14)\n                        gi->table_select[1] = 16;\n                    writeheader(gfc, gi->table_select[1], 5);\n                    if (gi->table_select[2] == 14)\n                        gi->table_select[2] = 16;\n                    writeheader(gfc, gi->table_select[2], 5);\n\n                    assert(0 <= gi->region0_count && gi->region0_count < 16);\n                    assert(0 <= gi->region1_count && gi->region1_count < 8);\n                    writeheader(gfc, gi->region0_count, 4);\n                    writeheader(gfc, gi->region1_count, 3);\n                }\n                writeheader(gfc, gi->preflag, 1);\n                writeheader(gfc, gi->scalefac_scale, 1);\n                writeheader(gfc, gi->count1table_select, 1);\n            }\n        }\n    }\n    else {\n        /* MPEG2 */\n        assert(l3_side->main_data_begin >= 0);\n        writeheader(gfc, (l3_side->main_data_begin), 8);\n        writeheader(gfc, l3_side->private_bits, cfg->channels_out);\n\n        gr = 0;\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            gr_info *const gi = &l3_side->tt[gr][ch];\n            writeheader(gfc, gi->part2_3_length + gi->part2_length, 12);\n            writeheader(gfc, gi->big_values / 2, 9);\n            writeheader(gfc, gi->global_gain, 8);\n            writeheader(gfc, gi->scalefac_compress, 9);\n\n            if (gi->block_type != NORM_TYPE) {\n                writeheader(gfc, 1, 1); /* window_switching_flag */\n                writeheader(gfc, gi->block_type, 2);\n                writeheader(gfc, gi->mixed_block_flag, 1);\n\n                if (gi->table_select[0] == 14)\n                    gi->table_select[0] = 16;\n                writeheader(gfc, gi->table_select[0], 5);\n                if (gi->table_select[1] == 14)\n                    gi->table_select[1] = 16;\n                writeheader(gfc, gi->table_select[1], 5);\n\n                writeheader(gfc, gi->subblock_gain[0], 3);\n                writeheader(gfc, gi->subblock_gain[1], 3);\n                writeheader(gfc, gi->subblock_gain[2], 3);\n            }\n            else {\n                writeheader(gfc, 0, 1); /* window_switching_flag */\n                if (gi->table_select[0] == 14)\n                    gi->table_select[0] = 16;\n                writeheader(gfc, gi->table_select[0], 5);\n                if (gi->table_select[1] == 14)\n                    gi->table_select[1] = 16;\n                writeheader(gfc, gi->table_select[1], 5);\n                if (gi->table_select[2] == 14)\n                    gi->table_select[2] = 16;\n                writeheader(gfc, gi->table_select[2], 5);\n\n                assert(0 <= gi->region0_count && gi->region0_count < 16);\n                assert(0 <= gi->region1_count && gi->region1_count < 8);\n                writeheader(gfc, gi->region0_count, 4);\n                writeheader(gfc, gi->region1_count, 3);\n            }\n\n            writeheader(gfc, gi->scalefac_scale, 1);\n            writeheader(gfc, gi->count1table_select, 1);\n        }\n    }\n\n    if (cfg->error_protection) {\n        /* (jo) error_protection: add crc16 information to header */\n        CRC_writeheader(gfc, esv->header[esv->h_ptr].buf);\n    }\n\n    {\n        int const old = esv->h_ptr;\n        assert(esv->header[old].ptr == cfg->sideinfo_len * 8);\n\n        esv->h_ptr = (old + 1) & (MAX_HEADER_BUF - 1);\n        esv->header[esv->h_ptr].write_timing = esv->header[old].write_timing + bitsPerFrame;\n\n        if (esv->h_ptr == esv->w_ptr) {\n            /* yikes! we are out of header buffer space */\n            ERRORF(gfc, \"Error: MAX_HEADER_BUF too small in bitstream.c \\n\");\n        }\n\n    }\n}\n\n\ninline static int\nhuffman_coder_count1(lame_internal_flags * gfc, gr_info const *gi)\n{\n    /* Write count1 area */\n    struct huffcodetab const *const h = &ht[gi->count1table_select + 32];\n    int     i, bits = 0;\n#ifdef DEBUG\n    int     gegebo = gfc->bs.totbit;\n#endif\n\n    int const *ix = &gi->l3_enc[gi->big_values];\n    FLOAT const *xr = &gi->xr[gi->big_values];\n    assert(gi->count1table_select < 2);\n\n    for (i = (gi->count1 - gi->big_values) / 4; i > 0; --i) {\n        int     huffbits = 0;\n        int     p = 0, v;\n\n        v = ix[0];\n        if (v) {\n            p += 8;\n            if (xr[0] < 0.0f)\n                huffbits++;\n            assert(v <= 1);\n        }\n\n        v = ix[1];\n        if (v) {\n            p += 4;\n            huffbits *= 2;\n            if (xr[1] < 0.0f)\n                huffbits++;\n            assert(v <= 1);\n        }\n\n        v = ix[2];\n        if (v) {\n            p += 2;\n            huffbits *= 2;\n            if (xr[2] < 0.0f)\n                huffbits++;\n            assert(v <= 1);\n        }\n\n        v = ix[3];\n        if (v) {\n            p++;\n            huffbits *= 2;\n            if (xr[3] < 0.0f)\n                huffbits++;\n            assert(v <= 1);\n        }\n\n        ix += 4;\n        xr += 4;\n        putbits2(gfc, huffbits + h->table[p], h->hlen[p]);\n        bits += h->hlen[p];\n    }\n#ifdef DEBUG\n    DEBUGF(gfc, \"count1: real: %ld counted:%d (bigv %d count1len %d)\\n\",\n           gfc->bs.totbit - gegebo, gi->count1bits, gi->big_values, gi->count1);\n#endif\n    return bits;\n}\n\n\n\n/*\n  Implements the pseudocode of page 98 of the IS\n  */\ninline static int\nHuffmancode(lame_internal_flags * const gfc, const unsigned int tableindex,\n            int start, int end, gr_info const *gi)\n{\n    struct huffcodetab const *const h = &ht[tableindex];\n    unsigned int const linbits = h->xlen;\n    int     i, bits = 0;\n\n    assert(tableindex < 32u);\n    if (!tableindex)\n        return bits;\n\n    for (i = start; i < end; i += 2) {\n        int16_t  cbits = 0;\n        uint16_t xbits = 0;\n        unsigned int xlen = h->xlen;\n        unsigned int ext = 0;\n        unsigned int x1 = gi->l3_enc[i];\n        unsigned int x2 = gi->l3_enc[i + 1];\n\n        assert(gi->l3_enc[i] >= 0);\n        assert(gi->l3_enc[i+1] >= 0);\n\n        if (x1 != 0u) {\n            if (gi->xr[i] < 0.0f)\n                ext++;\n            cbits--;\n        }\n\n        if (tableindex > 15u) {\n            /* use ESC-words */\n            if (x1 >= 15u) {\n                uint16_t const linbits_x1 = x1 - 15u;\n                assert(linbits_x1 <= h->linmax);\n                ext |= linbits_x1 << 1u;\n                xbits = linbits;\n                x1 = 15u;\n            }\n\n            if (x2 >= 15u) {\n                uint16_t const linbits_x2 = x2 - 15u;\n                assert(linbits_x2 <= h->linmax);\n                ext <<= linbits;\n                ext |= linbits_x2;\n                xbits += linbits;\n                x2 = 15u;\n            }\n            xlen = 16;\n        }\n\n        if (x2 != 0u) {\n            ext <<= 1;\n            if (gi->xr[i + 1] < 0.0f)\n                ext++;\n            cbits--;\n        }\n\n        assert((x1 | x2) < 16u);\n\n        x1 = x1 * xlen + x2;\n        xbits -= cbits;\n        cbits += h->hlen[x1];\n\n        assert(cbits <= MAX_LENGTH);\n        assert(xbits <= MAX_LENGTH);\n\n        putbits2(gfc, h->table[x1], cbits);\n        putbits2(gfc, (int)ext, xbits);\n        bits += cbits + xbits;\n    }\n    return bits;\n}\n\n/*\n  Note the discussion of huffmancodebits() on pages 28\n  and 29 of the IS, as well as the definitions of the side\n  information on pages 26 and 27.\n  */\nstatic int\nShortHuffmancodebits(lame_internal_flags * gfc, gr_info const *gi)\n{\n    int     bits;\n    int     region1Start;\n\n    region1Start = 3 * gfc->scalefac_band.s[3];\n    if (region1Start > gi->big_values)\n        region1Start = gi->big_values;\n\n    /* short blocks do not have a region2 */\n    bits = Huffmancode(gfc, gi->table_select[0], 0, region1Start, gi);\n    bits += Huffmancode(gfc, gi->table_select[1], region1Start, gi->big_values, gi);\n    return bits;\n}\n\nstatic int\nLongHuffmancodebits(lame_internal_flags * gfc, gr_info const *gi)\n{\n    unsigned int i;\n    int     bigvalues, bits;\n    int     region1Start, region2Start;\n\n    bigvalues = gi->big_values;\n    assert(0 <= bigvalues && bigvalues <= 576);\n\n    assert(gi->region0_count >= -1);\n    assert(gi->region1_count >= -1);\n    i = gi->region0_count + 1;\n    assert((size_t) i < dimension_of(gfc->scalefac_band.l));\n    region1Start = gfc->scalefac_band.l[i];\n    i += gi->region1_count + 1;\n    assert((size_t) i < dimension_of(gfc->scalefac_band.l));\n    region2Start = gfc->scalefac_band.l[i];\n\n    if (region1Start > bigvalues)\n        region1Start = bigvalues;\n\n    if (region2Start > bigvalues)\n        region2Start = bigvalues;\n\n    bits = Huffmancode(gfc, gi->table_select[0], 0, region1Start, gi);\n    bits += Huffmancode(gfc, gi->table_select[1], region1Start, region2Start, gi);\n    bits += Huffmancode(gfc, gi->table_select[2], region2Start, bigvalues, gi);\n    return bits;\n}\n\ninline static int\nwriteMainData(lame_internal_flags * const gfc)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    III_side_info_t const *const l3_side = &gfc->l3_side;\n    int     gr, ch, sfb, data_bits, tot_bits = 0;\n\n    if (cfg->version == 1) {\n        /* MPEG 1 */\n        for (gr = 0; gr < 2; gr++) {\n            for (ch = 0; ch < cfg->channels_out; ch++) {\n                gr_info const *const gi = &l3_side->tt[gr][ch];\n                int const slen1 = slen1_tab[gi->scalefac_compress];\n                int const slen2 = slen2_tab[gi->scalefac_compress];\n                data_bits = 0;\n#ifdef DEBUG\n                hogege = gfc->bs.totbit;\n#endif\n                for (sfb = 0; sfb < gi->sfbdivide; sfb++) {\n                    if (gi->scalefac[sfb] == -1)\n                        continue; /* scfsi is used */\n                    putbits2(gfc, gi->scalefac[sfb], slen1);\n                    data_bits += slen1;\n                }\n                for (; sfb < gi->sfbmax; sfb++) {\n                    if (gi->scalefac[sfb] == -1)\n                        continue; /* scfsi is used */\n                    putbits2(gfc, gi->scalefac[sfb], slen2);\n                    data_bits += slen2;\n                }\n                assert(data_bits == gi->part2_length);\n\n                if (gi->block_type == SHORT_TYPE) {\n                    data_bits += ShortHuffmancodebits(gfc, gi);\n                }\n                else {\n                    data_bits += LongHuffmancodebits(gfc, gi);\n                }\n                data_bits += huffman_coder_count1(gfc, gi);\n#ifdef DEBUG\n                DEBUGF(gfc, \"<%ld> \", gfc->bs.totbit - hogege);\n#endif\n                /* does bitcount in quantize.c agree with actual bit count? */\n                assert(data_bits == gi->part2_3_length + gi->part2_length);\n                tot_bits += data_bits;\n            }           /* for ch */\n        }               /* for gr */\n    }\n    else {\n        /* MPEG 2 */\n        gr = 0;\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            gr_info const *const gi = &l3_side->tt[gr][ch];\n            int     i, sfb_partition, scale_bits = 0;\n            assert(gi->sfb_partition_table);\n            data_bits = 0;\n#ifdef DEBUG\n            hogege = gfc->bs.totbit;\n#endif\n            sfb = 0;\n            sfb_partition = 0;\n\n            if (gi->block_type == SHORT_TYPE) {\n                for (; sfb_partition < 4; sfb_partition++) {\n                    int const sfbs = gi->sfb_partition_table[sfb_partition] / 3;\n                    int const slen = gi->slen[sfb_partition];\n                    for (i = 0; i < sfbs; i++, sfb++) {\n                        putbits2(gfc, Max(gi->scalefac[sfb * 3 + 0], 0), slen);\n                        putbits2(gfc, Max(gi->scalefac[sfb * 3 + 1], 0), slen);\n                        putbits2(gfc, Max(gi->scalefac[sfb * 3 + 2], 0), slen);\n                        scale_bits += 3 * slen;\n                    }\n                }\n                data_bits += ShortHuffmancodebits(gfc, gi);\n            }\n            else {\n                for (; sfb_partition < 4; sfb_partition++) {\n                    int const sfbs = gi->sfb_partition_table[sfb_partition];\n                    int const slen = gi->slen[sfb_partition];\n                    for (i = 0; i < sfbs; i++, sfb++) {\n                        putbits2(gfc, Max(gi->scalefac[sfb], 0), slen);\n                        scale_bits += slen;\n                    }\n                }\n                data_bits += LongHuffmancodebits(gfc, gi);\n            }\n            data_bits += huffman_coder_count1(gfc, gi);\n#ifdef DEBUG\n            DEBUGF(gfc, \"<%ld> \", gfc->bs.totbit - hogege);\n#endif\n            /* does bitcount in quantize.c agree with actual bit count? */\n            assert(data_bits == gi->part2_3_length);\n            assert(scale_bits == gi->part2_length);\n            tot_bits += scale_bits + data_bits;\n        }               /* for ch */\n    }                   /* for gf */\n    return tot_bits;\n}                       /* main_data */\n\n\n\n/* compute the number of bits required to flush all mp3 frames\n   currently in the buffer.  This should be the same as the\n   reservoir size.  Only call this routine between frames - i.e.\n   only after all headers and data have been added to the buffer\n   by format_bitstream().\n\n   Also compute total_bits_output =\n       size of mp3 buffer (including frame headers which may not\n       have yet been send to the mp3 buffer) +\n       number of bits needed to flush all mp3 frames.\n\n   total_bytes_output is the size of the mp3 output buffer if\n   lame_encode_flush_nogap() was called right now.\n\n */\nint\ncompute_flushbits(const lame_internal_flags * gfc, int *total_bytes_output)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncStateVar_t const *const esv = &gfc->sv_enc;\n    int     flushbits, remaining_headers;\n    int     bitsPerFrame;\n    int     last_ptr, first_ptr;\n    first_ptr = esv->w_ptr; /* first header to add to bitstream */\n    last_ptr = esv->h_ptr - 1; /* last header to add to bitstream */\n    if (last_ptr == -1)\n        last_ptr = MAX_HEADER_BUF - 1;\n\n    /* add this many bits to bitstream so we can flush all headers */\n    flushbits = esv->header[last_ptr].write_timing - gfc->bs.totbit;\n    *total_bytes_output = flushbits;\n\n    if (flushbits >= 0) {\n        /* if flushbits >= 0, some headers have not yet been written */\n        /* reduce flushbits by the size of the headers */\n        remaining_headers = 1 + last_ptr - first_ptr;\n        if (last_ptr < first_ptr)\n            remaining_headers = 1 + last_ptr - first_ptr + MAX_HEADER_BUF;\n        flushbits -= remaining_headers * 8 * cfg->sideinfo_len;\n    }\n\n\n    /* finally, add some bits so that the last frame is complete\n     * these bits are not necessary to decode the last frame, but\n     * some decoders will ignore last frame if these bits are missing\n     */\n    bitsPerFrame = getframebits(gfc);\n    flushbits += bitsPerFrame;\n    *total_bytes_output += bitsPerFrame;\n    /* round up:   */\n    if (*total_bytes_output % 8)\n        *total_bytes_output = 1 + (*total_bytes_output / 8);\n    else\n        *total_bytes_output = (*total_bytes_output / 8);\n    *total_bytes_output += gfc->bs.buf_byte_idx + 1;\n\n\n    if (flushbits < 0) {\n#if 0\n        /* if flushbits < 0, this would mean that the buffer looks like:\n         * (data...)  last_header  (data...)  (extra data that should not be here...)\n         */\n        DEBUGF(gfc, \"last header write_timing = %i \\n\", esv->header[last_ptr].write_timing);\n        DEBUGF(gfc, \"first header write_timing = %i \\n\", esv->header[first_ptr].write_timing);\n        DEBUGF(gfc, \"bs.totbit:                 %i \\n\", gfc->bs.totbit);\n        DEBUGF(gfc, \"first_ptr, last_ptr        %i %i \\n\", first_ptr, last_ptr);\n        DEBUGF(gfc, \"remaining_headers =        %i \\n\", remaining_headers);\n        DEBUGF(gfc, \"bitsperframe:              %i \\n\", bitsPerFrame);\n        DEBUGF(gfc, \"sidelen:                   %i \\n\", cfg->sideinfo_len);\n#endif\n        ERRORF(gfc, \"strange error flushing buffer ... \\n\");\n    }\n    return flushbits;\n}\n\n\nvoid\nflush_bitstream(lame_internal_flags * gfc)\n{\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    III_side_info_t *l3_side;\n    int     nbytes;\n    int     flushbits;\n    int     last_ptr = esv->h_ptr - 1; /* last header to add to bitstream */\n    if (last_ptr == -1)\n        last_ptr = MAX_HEADER_BUF - 1;\n    l3_side = &gfc->l3_side;\n\n\n    if ((flushbits = compute_flushbits(gfc, &nbytes)) < 0)\n        return;\n    drain_into_ancillary(gfc, flushbits);\n\n    /* check that the 100% of the last frame has been written to bitstream */\n    assert(esv->header[last_ptr].write_timing + getframebits(gfc)\n           == gfc->bs.totbit);\n\n    /* we have padded out all frames with ancillary data, which is the\n       same as filling the bitreservoir with ancillary data, so : */\n    esv->ResvSize = 0;\n    l3_side->main_data_begin = 0;\n}\n\n\n\n\nvoid\nadd_dummy_byte(lame_internal_flags * gfc, unsigned char val, unsigned int n)\n{\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    int     i;\n\n    while (n-- > 0u) {\n        putbits_noheaders(gfc, val, 8);\n\n        for (i = 0; i < MAX_HEADER_BUF; ++i)\n            esv->header[i].write_timing += 8;\n    }\n}\n\n\n/*\n  format_bitstream()\n\n  This is called after a frame of audio has been quantized and coded.\n  It will write the encoded audio to the bitstream. Note that\n  from a layer3 encoder's perspective the bit stream is primarily\n  a series of main_data() blocks, with header and side information\n  inserted at the proper locations to maintain framing. (See Figure A.7\n  in the IS).\n  */\nint\nformat_bitstream(lame_internal_flags * gfc)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    int     bits, nbytes;\n    III_side_info_t *l3_side;\n    int     bitsPerFrame;\n    l3_side = &gfc->l3_side;\n\n    bitsPerFrame = getframebits(gfc);\n    drain_into_ancillary(gfc, l3_side->resvDrain_pre);\n\n    encodeSideInfo2(gfc, bitsPerFrame);\n    bits = 8 * cfg->sideinfo_len;\n    bits += writeMainData(gfc);\n    drain_into_ancillary(gfc, l3_side->resvDrain_post);\n    bits += l3_side->resvDrain_post;\n\n    l3_side->main_data_begin += (bitsPerFrame - bits) / 8;\n\n    /* compare number of bits needed to clear all buffered mp3 frames\n     * with what we think the resvsize is: */\n    if (compute_flushbits(gfc, &nbytes) != esv->ResvSize) {\n        ERRORF(gfc, \"Internal buffer inconsistency. flushbits <> ResvSize\");\n    }\n\n\n    /* compare main_data_begin for the next frame with what we\n     * think the resvsize is: */\n    if ((l3_side->main_data_begin * 8) != esv->ResvSize) {\n        ERRORF(gfc, \"bit reservoir error: \\n\"\n               \"l3_side->main_data_begin: %i \\n\"\n               \"Resvoir size:             %i \\n\"\n               \"resv drain (post)         %i \\n\"\n               \"resv drain (pre)          %i \\n\"\n               \"header and sideinfo:      %i \\n\"\n               \"data bits:                %i \\n\"\n               \"total bits:               %i (remainder: %i) \\n\"\n               \"bitsperframe:             %i \\n\",\n               8 * l3_side->main_data_begin,\n               esv->ResvSize,\n               l3_side->resvDrain_post,\n               l3_side->resvDrain_pre,\n               8 * cfg->sideinfo_len,\n               bits - l3_side->resvDrain_post - 8 * cfg->sideinfo_len,\n               bits, bits % 8, bitsPerFrame);\n\n        ERRORF(gfc, \"This is a fatal error.  It has several possible causes:\");\n        ERRORF(gfc, \"90%%  LAME compiled with buggy version of gcc using advanced optimizations\");\n        ERRORF(gfc, \" 9%%  Your system is overclocked\");\n        ERRORF(gfc, \" 1%%  bug in LAME encoding library\");\n\n        esv->ResvSize = l3_side->main_data_begin * 8;\n    };\n    assert(gfc->bs.totbit % 8 == 0);\n\n    if (gfc->bs.totbit > 1000000000) {\n        /* to avoid totbit overflow, (at 8h encoding at 128kbs) lets reset bit counter */\n        int     i;\n        for (i = 0; i < MAX_HEADER_BUF; ++i)\n            esv->header[i].write_timing -= gfc->bs.totbit;\n        gfc->bs.totbit = 0;\n    }\n\n\n    return 0;\n}\n\n\nstatic int\ndo_gain_analysis(lame_internal_flags * gfc, unsigned char* buffer, int minimum)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    RpgStateVar_t const *const rsv = &gfc->sv_rpg;\n    RpgResult_t *const rov = &gfc->ov_rpg;\n#ifdef DECODE_ON_THE_FLY\n    if (cfg->decode_on_the_fly) { /* decode the frame */\n        sample_t pcm_buf[2][1152];\n        int     mp3_in = minimum;\n        int     samples_out = -1;\n\n        /* re-synthesis to pcm.  Repeat until we get a samples_out=0 */\n        while (samples_out != 0) {\n\n            samples_out = hip_decode1_unclipped(gfc->hip, buffer, mp3_in, pcm_buf[0], pcm_buf[1]);\n            /* samples_out = 0:  need more data to decode\n             * samples_out = -1:  error.  Lets assume 0 pcm output\n             * samples_out = number of samples output */\n\n            /* set the lenght of the mp3 input buffer to zero, so that in the\n             * next iteration of the loop we will be querying mpglib about\n             * buffered data */\n            mp3_in = 0;\n\n            if (samples_out == -1) {\n                /* error decoding. Not fatal, but might screw up\n                 * the ReplayGain tag. What should we do? Ignore for now */\n                samples_out = 0;\n            }\n            if (samples_out > 0) {\n                /* process the PCM data */\n\n                /* this should not be possible, and indicates we have\n                 * overflown the pcm_buf buffer */\n                assert(samples_out <= 1152);\n\n                if (cfg->findPeakSample) {\n                    int     i;\n                    /* FIXME: is this correct? maybe Max(fabs(pcm),PeakSample) */\n                    for (i = 0; i < samples_out; i++) {\n                        if (pcm_buf[0][i] > rov->PeakSample)\n                            rov->PeakSample = pcm_buf[0][i];\n                        else if (-pcm_buf[0][i] > rov->PeakSample)\n                            rov->PeakSample = -pcm_buf[0][i];\n                    }\n                    if (cfg->channels_out > 1)\n                        for (i = 0; i < samples_out; i++) {\n                            if (pcm_buf[1][i] > rov->PeakSample)\n                                rov->PeakSample = pcm_buf[1][i];\n                            else if (-pcm_buf[1][i] > rov->PeakSample)\n                                rov->PeakSample = -pcm_buf[1][i];\n                        }\n                }\n\n                if (cfg->findReplayGain)\n                    if (AnalyzeSamples\n                        (rsv->rgdata, pcm_buf[0], pcm_buf[1], samples_out,\n                         cfg->channels_out) == GAIN_ANALYSIS_ERROR)\n                        return -6;\n\n            }       /* if (samples_out>0) */\n        }           /* while (samples_out!=0) */\n    }               /* if (gfc->decode_on_the_fly) */\n#endif\n    return minimum;\n}\n\nstatic int\ndo_copy_buffer(lame_internal_flags * gfc, unsigned char *buffer, int size)\n{\n    Bit_stream_struc *const bs = &gfc->bs;\n    int const minimum = bs->buf_byte_idx + 1;\n    if (minimum <= 0)\n        return 0;\n    if (size != 0 && minimum > size)\n        return -1;      /* buffer is too small */\n    memcpy(buffer, bs->buf, minimum);\n\n//    bcopy(buffer, bs->buf, minimum);\n\n    bs->buf_byte_idx = -1;\n    bs->buf_bit_idx = 0;\n    return minimum;\n}\n\n/* copy data out of the internal MP3 bit buffer into a user supplied\n   unsigned char buffer.\n\n   mp3data=0      indicates data in buffer is an id3tags and VBR tags\n   mp3data=1      data is real mp3 frame data.\n\n\n*/\nint\ncopy_buffer(lame_internal_flags * gfc, unsigned char *buffer, int size, int mp3data)\n{\n    int const minimum = do_copy_buffer(gfc, buffer, size);\n    if (minimum > 0 && mp3data) {\n        UpdateMusicCRC(&gfc->nMusicCRC, buffer, minimum);\n\n        /** sum number of bytes belonging to the mp3 stream\n         *  this info will be written into the Xing/LAME header for seeking\n         */\n        gfc->VBR_seek_table.nBytesWritten += minimum;\n\n        return do_gain_analysis(gfc, buffer, minimum);\n    }                   /* if (mp3data) */\n    return minimum;\n}\n\n\nvoid\ninit_bit_stream_w(lame_internal_flags * gfc)\n{\n    EncStateVar_t *const esv = &gfc->sv_enc;\n\n    esv->h_ptr = esv->w_ptr = 0;\n    esv->header[esv->h_ptr].write_timing = 0;\n\n    gfc->bs.buf = (unsigned char *) malloc(BUFFER_SIZE);\n    gfc->bs.buf_size = BUFFER_SIZE;\n    gfc->bs.buf_byte_idx = -1;\n    gfc->bs.buf_bit_idx = 0;\n    gfc->bs.totbit = 0;\n}\n\n/* end of bitstream.c */\n"
  },
  {
    "path": "app/jni/libmp3lame/bitstream.h",
    "content": "/*\n *\tMP3 bitstream Output interface for LAME\n *\n *\tCopyright (c) 1999 Takehiro TOMINAGA\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_BITSTREAM_H\n#define LAME_BITSTREAM_H\n\nint     getframebits(const lame_internal_flags * gfc);\n\nint     format_bitstream(lame_internal_flags * gfc);\n\nvoid    flush_bitstream(lame_internal_flags * gfc);\nvoid    add_dummy_byte(lame_internal_flags * gfc, unsigned char val, unsigned int n);\n\nint     copy_buffer(lame_internal_flags * gfc, unsigned char *buffer, int buffer_size,\n                    int update_crc);\nvoid    init_bit_stream_w(lame_internal_flags * gfc);\nvoid    CRC_writeheader(lame_internal_flags const *gfc, char *buffer);\nint     compute_flushbits(const lame_internal_flags * gfp, int *nbytes);\n\nint     get_max_frame_buffer_size_by_constraint(SessionConfig_t const * cfg, int constraint);\n\n#endif\n"
  },
  {
    "path": "app/jni/libmp3lame/encoder.c",
    "content": "/*\n *      LAME MP3 encoding engine\n *\n *      Copyright (c) 1999 Mark Taylor\n *      Copyright (c) 2000-2002 Takehiro Tominaga\n *      Copyright (c) 2000-2011 Robert Hegemann\n *      Copyright (c) 2001 Gabriel Bouvigne\n *      Copyright (c) 2001 John Dahlstrom\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: encoder.c,v 1.111 2011/05/07 16:05:17 rbrito Exp $ */\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n\n#include <string.h>\n#include <strings.h>\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"lame_global_flags.h\"\n#include \"newmdct.h\"\n#include \"psymodel.h\"\n#include \"lame-analysis.h\"\n#include \"bitstream.h\"\n#include \"VbrTag.h\"\n#include \"quantize_pvt.h\"\n\n\n\n/*\n * auto-adjust of ATH, useful for low volume\n * Gabriel Bouvigne 3 feb 2001\n *\n * modifies some values in\n *   gfp->internal_flags->ATH\n *   (gfc->ATH)\n */\nstatic void\nadjust_ATH(lame_internal_flags const *const gfc)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    FLOAT   gr2_max, max_pow;\n\n    if (gfc->ATH->use_adjust == 0) {\n        gfc->ATH->adjust_factor = 1.0; /* no adjustment */\n        return;\n    }\n\n    /* jd - 2001 mar 12, 27, jun 30 */\n    /* loudness based on equal loudness curve; */\n    /* use granule with maximum combined loudness */\n    max_pow = gfc->ov_psy.loudness_sq[0][0];\n    gr2_max = gfc->ov_psy.loudness_sq[1][0];\n    if (cfg->channels_out == 2) {\n        max_pow += gfc->ov_psy.loudness_sq[0][1];\n        gr2_max += gfc->ov_psy.loudness_sq[1][1];\n    }\n    else {\n        max_pow += max_pow;\n        gr2_max += gr2_max;\n    }\n    if (cfg->mode_gr == 2) {\n        max_pow = Max(max_pow, gr2_max);\n    }\n    max_pow *= 0.5;     /* max_pow approaches 1.0 for full band noise */\n\n    /* jd - 2001 mar 31, jun 30 */\n    /* user tuning of ATH adjustment region */\n    max_pow *= gfc->ATH->aa_sensitivity_p;\n\n    /*  adjust ATH depending on range of maximum value\n     */\n\n    /* jd - 2001 feb27, mar12,20, jun30, jul22 */\n    /* continuous curves based on approximation */\n    /* to GB's original values. */\n    /* For an increase in approximate loudness, */\n    /* set ATH adjust to adjust_limit immediately */\n    /* after a delay of one frame. */\n    /* For a loudness decrease, reduce ATH adjust */\n    /* towards adjust_limit gradually. */\n    /* max_pow is a loudness squared or a power. */\n    if (max_pow > 0.03125) { /* ((1 - 0.000625)/ 31.98) from curve below */\n        if (gfc->ATH->adjust_factor >= 1.0) {\n            gfc->ATH->adjust_factor = 1.0;\n        }\n        else {\n            /* preceding frame has lower ATH adjust; */\n            /* ascend only to the preceding adjust_limit */\n            /* in case there is leading low volume */\n            if (gfc->ATH->adjust_factor < gfc->ATH->adjust_limit) {\n                gfc->ATH->adjust_factor = gfc->ATH->adjust_limit;\n            }\n        }\n        gfc->ATH->adjust_limit = 1.0;\n    }\n    else {              /* adjustment curve */\n        /* about 32 dB maximum adjust (0.000625) */\n        FLOAT const adj_lim_new = 31.98 * max_pow + 0.000625;\n        if (gfc->ATH->adjust_factor >= adj_lim_new) { /* descend gradually */\n            gfc->ATH->adjust_factor *= adj_lim_new * 0.075 + 0.925;\n            if (gfc->ATH->adjust_factor < adj_lim_new) { /* stop descent */\n                gfc->ATH->adjust_factor = adj_lim_new;\n            }\n        }\n        else {          /* ascend */\n            if (gfc->ATH->adjust_limit >= adj_lim_new) {\n                gfc->ATH->adjust_factor = adj_lim_new;\n            }\n            else {      /* preceding frame has lower ATH adjust; */\n                /* ascend only to the preceding adjust_limit */\n                if (gfc->ATH->adjust_factor < gfc->ATH->adjust_limit) {\n                    gfc->ATH->adjust_factor = gfc->ATH->adjust_limit;\n                }\n            }\n        }\n        gfc->ATH->adjust_limit = adj_lim_new;\n    }\n}\n\n/***********************************************************************\n *\n *  some simple statistics\n *\n *  bitrate index 0: free bitrate -> not allowed in VBR mode\n *  : bitrates, kbps depending on MPEG version\n *  bitrate index 15: forbidden\n *\n *  mode_ext:\n *  0:  LR\n *  1:  LR-i\n *  2:  MS\n *  3:  MS-i\n *\n ***********************************************************************/\n\nstatic void\nupdateStats(lame_internal_flags * const gfc)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncResult_t *eov = &gfc->ov_enc;\n    int     gr, ch;\n    assert(0 <= eov->bitrate_index && eov->bitrate_index < 16);\n    assert(0 <= eov->mode_ext && eov->mode_ext < 4);\n\n    /* count bitrate indices */\n    eov->bitrate_channelmode_hist[eov->bitrate_index][4]++;\n    eov->bitrate_channelmode_hist[15][4]++;\n\n    /* count 'em for every mode extension in case of 2 channel encoding */\n    if (cfg->channels_out == 2) {\n        eov->bitrate_channelmode_hist[eov->bitrate_index][eov->mode_ext]++;\n        eov->bitrate_channelmode_hist[15][eov->mode_ext]++;\n    }\n    for (gr = 0; gr < cfg->mode_gr; ++gr) {\n        for (ch = 0; ch < cfg->channels_out; ++ch) {\n            int     bt = gfc->l3_side.tt[gr][ch].block_type;\n            if (gfc->l3_side.tt[gr][ch].mixed_block_flag)\n                bt = 4;\n            eov->bitrate_blocktype_hist[eov->bitrate_index][bt]++;\n            eov->bitrate_blocktype_hist[eov->bitrate_index][5]++;\n            eov->bitrate_blocktype_hist[15][bt]++;\n            eov->bitrate_blocktype_hist[15][5]++;\n        }\n    }\n}\n\n\n\n\nstatic void\nlame_encode_frame_init(lame_internal_flags * gfc, const sample_t *const inbuf[2])\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n\n    int     ch, gr;\n\n    if (gfc->lame_encode_frame_init == 0) {\n        sample_t primebuff0[286 + 1152 + 576];\n        sample_t primebuff1[286 + 1152 + 576];\n        int const framesize = 576 * cfg->mode_gr;\n        /* prime the MDCT/polyphase filterbank with a short block */\n        int     i, j;\n        gfc->lame_encode_frame_init = 1;\n        memset(primebuff0, 0, sizeof(primebuff0));\n        memset(primebuff1, 0, sizeof(primebuff1));\n        for (i = 0, j = 0; i < 286 + 576 * (1 + cfg->mode_gr); ++i) {\n            if (i < framesize) {\n                primebuff0[i] = 0;\n                if (cfg->channels_out == 2)\n                    primebuff1[i] = 0;\n            }\n            else {\n                primebuff0[i] = inbuf[0][j];\n                if (cfg->channels_out == 2)\n                    primebuff1[i] = inbuf[1][j];\n                ++j;\n            }\n        }\n        /* polyphase filtering / mdct */\n        for (gr = 0; gr < cfg->mode_gr; gr++) {\n            for (ch = 0; ch < cfg->channels_out; ch++) {\n                gfc->l3_side.tt[gr][ch].block_type = SHORT_TYPE;\n            }\n        }\n        mdct_sub48(gfc, primebuff0, primebuff1);\n\n        /* check FFT will not use a negative starting offset */\n#if 576 < FFTOFFSET\n# error FFTOFFSET greater than 576: FFT uses a negative offset\n#endif\n        /* check if we have enough data for FFT */\n        assert(gfc->sv_enc.mf_size >= (BLKSIZE + framesize - FFTOFFSET));\n        /* check if we have enough data for polyphase filterbank */\n        assert(gfc->sv_enc.mf_size >= (512 + framesize - 32));\n    }\n\n}\n\n\n\n\n\n\n\n/************************************************************************\n*\n* encodeframe()           Layer 3\n*\n* encode a single frame\n*\n************************************************************************\nlame_encode_frame()\n\n\n                       gr 0            gr 1\ninbuf:           |--------------|--------------|--------------|\n\n\nPolyphase (18 windows, each shifted 32)\ngr 0:\nwindow1          <----512---->\nwindow18                 <----512---->\n\ngr 1:\nwindow1                         <----512---->\nwindow18                                <----512---->\n\n\n\nMDCT output:  |--------------|--------------|--------------|\n\nFFT's                    <---------1024---------->\n                                         <---------1024-------->\n\n\n\n    inbuf = buffer of PCM data size=MP3 framesize\n    encoder acts on inbuf[ch][0], but output is delayed by MDCTDELAY\n    so the MDCT coefficints are from inbuf[ch][-MDCTDELAY]\n\n    psy-model FFT has a 1 granule delay, so we feed it data for the \n    next granule.\n    FFT is centered over granule:  224+576+224\n    So FFT starts at:   576-224-MDCTDELAY\n\n    MPEG2:  FFT ends at:  BLKSIZE+576-224-MDCTDELAY      (1328)\n    MPEG1:  FFT ends at:  BLKSIZE+2*576-224-MDCTDELAY    (1904)\n\n    MPEG2:  polyphase first window:  [0..511]\n                      18th window:   [544..1055]          (1056)\n    MPEG1:            36th window:   [1120..1631]         (1632)\n            data needed:  512+framesize-32\n\n    A close look newmdct.c shows that the polyphase filterbank\n    only uses data from [0..510] for each window.  Perhaps because the window\n    used by the filterbank is zero for the last point, so Takehiro's\n    code doesn't bother to compute with it.\n\n    FFT starts at 576-224-MDCTDELAY (304)  = 576-FFTOFFSET\n\n*/\n\ntypedef FLOAT chgrdata[2][2];\n\n\nint\nlame_encode_mp3_frame(       /* Output */\n                         lame_internal_flags * gfc, /* Context */\n                         sample_t const *inbuf_l, /* Input */\n                         sample_t const *inbuf_r, /* Input */\n                         unsigned char *mp3buf, /* Output */\n                         int mp3buf_size)\n{                       /* Output */\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     mp3count;\n    III_psy_ratio masking_LR[2][2]; /*LR masking & energy */\n    III_psy_ratio masking_MS[2][2]; /*MS masking & energy */\n    const III_psy_ratio (*masking)[2]; /*pointer to selected maskings */\n    const sample_t *inbuf[2];\n\n    FLOAT   tot_ener[2][4];\n    FLOAT   ms_ener_ratio[2] = { .5, .5 };\n    FLOAT   pe[2][2] = { {0., 0.}, {0., 0.} }, pe_MS[2][2] = { {\n    0., 0.}, {\n    0., 0.}};\n    FLOAT (*pe_use)[2];\n\n    int     ch, gr;\n\n    inbuf[0] = inbuf_l;\n    inbuf[1] = inbuf_r;\n\n    if (gfc->lame_encode_frame_init == 0) {\n        /*first run? */\n        lame_encode_frame_init(gfc, inbuf);\n\n    }\n\n\n    /********************** padding *****************************/\n    /* padding method as described in \n     * \"MPEG-Layer3 / Bitstream Syntax and Decoding\"\n     * by Martin Sieler, Ralph Sperschneider\n     *\n     * note: there is no padding for the very first frame\n     *\n     * Robert Hegemann 2000-06-22\n     */\n    gfc->ov_enc.padding = FALSE;\n    if ((gfc->sv_enc.slot_lag -= gfc->sv_enc.frac_SpF) < 0) {\n        gfc->sv_enc.slot_lag += cfg->samplerate_out;\n        gfc->ov_enc.padding = TRUE;\n    }\n\n\n\n    /****************************************\n    *   Stage 1: psychoacoustic model       *\n    ****************************************/\n\n    {\n        /* psychoacoustic model\n         * psy model has a 1 granule (576) delay that we must compensate for\n         * (mt 6/99).\n         */\n        int     ret;\n        const sample_t *bufp[2] = {0, 0}; /* address of beginning of left & right granule */\n        int     blocktype[2];\n\n        for (gr = 0; gr < cfg->mode_gr; gr++) {\n\n            for (ch = 0; ch < cfg->channels_out; ch++) {\n                bufp[ch] = &inbuf[ch][576 + gr * 576 - FFTOFFSET];\n            }\n            ret = L3psycho_anal_vbr(gfc, bufp, gr,\n                                    masking_LR, masking_MS,\n                                    pe[gr], pe_MS[gr], tot_ener[gr], blocktype);\n            if (ret != 0)\n                return -4;\n\n            if (cfg->mode == JOINT_STEREO) {\n                ms_ener_ratio[gr] = tot_ener[gr][2] + tot_ener[gr][3];\n                if (ms_ener_ratio[gr] > 0)\n                    ms_ener_ratio[gr] = tot_ener[gr][3] / ms_ener_ratio[gr];\n            }\n\n            /* block type flags */\n            for (ch = 0; ch < cfg->channels_out; ch++) {\n                gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];\n                cod_info->block_type = blocktype[ch];\n                cod_info->mixed_block_flag = 0;\n            }\n        }\n    }\n\n\n    /* auto-adjust of ATH, useful for low volume */\n    adjust_ATH(gfc);\n\n\n    /****************************************\n    *   Stage 2: MDCT                       *\n    ****************************************/\n\n    /* polyphase filtering / mdct */\n    mdct_sub48(gfc, inbuf[0], inbuf[1]);\n\n\n    /****************************************\n    *   Stage 3: MS/LR decision             *\n    ****************************************/\n\n    /* Here will be selected MS or LR coding of the 2 stereo channels */\n    gfc->ov_enc.mode_ext = MPG_MD_LR_LR;\n\n    if (cfg->force_ms) {\n        gfc->ov_enc.mode_ext = MPG_MD_MS_LR;\n    }\n    else if (cfg->mode == JOINT_STEREO) {\n        /* ms_ratio = is scaled, for historical reasons, to look like\n           a ratio of side_channel / total.\n           0 = signal is 100% mono\n           .5 = L & R uncorrelated\n         */\n\n        /* [0] and [1] are the results for the two granules in MPEG-1,\n         * in MPEG-2 it's only a faked averaging of the same value\n         * _prev is the value of the last granule of the previous frame\n         * _next is the value of the first granule of the next frame\n         */\n\n        FLOAT   sum_pe_MS = 0;\n        FLOAT   sum_pe_LR = 0;\n        for (gr = 0; gr < cfg->mode_gr; gr++) {\n            for (ch = 0; ch < cfg->channels_out; ch++) {\n                sum_pe_MS += pe_MS[gr][ch];\n                sum_pe_LR += pe[gr][ch];\n            }\n        }\n\n        /* based on PE: M/S coding would not use much more bits than L/R */\n        if (sum_pe_MS <= 1.00 * sum_pe_LR) {\n\n            gr_info const *const gi0 = &gfc->l3_side.tt[0][0];\n            gr_info const *const gi1 = &gfc->l3_side.tt[cfg->mode_gr - 1][0];\n\n            if (gi0[0].block_type == gi0[1].block_type && gi1[0].block_type == gi1[1].block_type) {\n\n                gfc->ov_enc.mode_ext = MPG_MD_MS_LR;\n            }\n        }\n    }\n\n    /* bit and noise allocation */\n    if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {\n        masking = (const III_psy_ratio (*)[2])masking_MS; /* use MS masking */\n        pe_use = pe_MS;\n    }\n    else {\n        masking = (const III_psy_ratio (*)[2])masking_LR; /* use LR masking */\n        pe_use = pe;\n    }\n\n\n    /* copy data for MP3 frame analyzer */\n    if (cfg->analysis && gfc->pinfo != NULL) {\n        for (gr = 0; gr < cfg->mode_gr; gr++) {\n            for (ch = 0; ch < cfg->channels_out; ch++) {\n                gfc->pinfo->ms_ratio[gr] = 0;\n                gfc->pinfo->ms_ener_ratio[gr] = ms_ener_ratio[gr];\n                gfc->pinfo->blocktype[gr][ch] = gfc->l3_side.tt[gr][ch].block_type;\n                gfc->pinfo->pe[gr][ch] = pe_use[gr][ch];\n                memcpy(gfc->pinfo->xr[gr][ch], &gfc->l3_side.tt[gr][ch].xr[0], sizeof(FLOAT) * 576);\n                /* in psymodel, LR and MS data was stored in pinfo.  \n                   switch to MS data: */\n                if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {\n                    gfc->pinfo->ers[gr][ch] = gfc->pinfo->ers[gr][ch + 2];\n                    memcpy(gfc->pinfo->energy[gr][ch], gfc->pinfo->energy[gr][ch + 2],\n                           sizeof(gfc->pinfo->energy[gr][ch]));\n                }\n            }\n        }\n    }\n\n\n    /****************************************\n    *   Stage 4: quantization loop          *\n    ****************************************/\n\n    if (cfg->vbr == vbr_off || cfg->vbr == vbr_abr) {\n        static FLOAT const fircoef[9] = {\n            -0.0207887 * 5, -0.0378413 * 5, -0.0432472 * 5, -0.031183 * 5,\n            7.79609e-18 * 5, 0.0467745 * 5, 0.10091 * 5, 0.151365 * 5,\n            0.187098 * 5\n        };\n\n        int     i;\n        FLOAT   f;\n\n        for (i = 0; i < 18; i++)\n            gfc->sv_enc.pefirbuf[i] = gfc->sv_enc.pefirbuf[i + 1];\n\n        f = 0.0;\n        for (gr = 0; gr < cfg->mode_gr; gr++)\n            for (ch = 0; ch < cfg->channels_out; ch++)\n                f += pe_use[gr][ch];\n        gfc->sv_enc.pefirbuf[18] = f;\n\n        f = gfc->sv_enc.pefirbuf[9];\n        for (i = 0; i < 9; i++)\n            f += (gfc->sv_enc.pefirbuf[i] + gfc->sv_enc.pefirbuf[18 - i]) * fircoef[i];\n\n        f = (670 * 5 * cfg->mode_gr * cfg->channels_out) / f;\n        for (gr = 0; gr < cfg->mode_gr; gr++) {\n            for (ch = 0; ch < cfg->channels_out; ch++) {\n                pe_use[gr][ch] *= f;\n            }\n        }\n    }\n    gfc->iteration_loop(gfc, (const FLOAT (*)[2])pe_use, ms_ener_ratio, masking);\n\n\n    /****************************************\n    *   Stage 5: bitstream formatting       *\n    ****************************************/\n\n\n    /*  write the frame to the bitstream  */\n    (void) format_bitstream(gfc);\n\n    /* copy mp3 bit buffer into array */\n    mp3count = copy_buffer(gfc, mp3buf, mp3buf_size, 1);\n\n\n    if (cfg->write_lame_tag) {\n        AddVbrFrame(gfc);\n    }\n\n    if (cfg->analysis && gfc->pinfo != NULL) {\n        int     framesize = 576 * cfg->mode_gr;\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            int     j;\n            for (j = 0; j < FFTOFFSET; j++)\n                gfc->pinfo->pcmdata[ch][j] = gfc->pinfo->pcmdata[ch][j + framesize];\n            for (j = FFTOFFSET; j < 1600; j++) {\n                gfc->pinfo->pcmdata[ch][j] = inbuf[ch][j - FFTOFFSET];\n            }\n        }\n        gfc->sv_qnt.masking_lower = 1.0;\n\n        set_frame_pinfo(gfc, masking);\n    }\n\n    ++gfc->ov_enc.frame_number;\n\n    updateStats(gfc);\n\n    return mp3count;\n}\n"
  },
  {
    "path": "app/jni/libmp3lame/encoder.h",
    "content": "/*\n *      encoder.h include file\n *\n *      Copyright (c) 2000 Mark Taylor\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n\n#ifndef LAME_ENCODER_H\n#define LAME_ENCODER_H\n\n/***********************************************************************\n*\n*  encoder and decoder delays\n*\n***********************************************************************/\n\n/* \n * layer III enc->dec delay:  1056 (1057?)   (observed)\n * layer  II enc->dec delay:   480  (481?)   (observed)\n *\n * polyphase 256-16             (dec or enc)        = 240\n * mdct      256+32  (9*32)     (dec or enc)        = 288\n * total:    512+16\n *\n * My guess is that delay of polyphase filterbank is actualy 240.5\n * (there are technical reasons for this, see postings in mp3encoder).\n * So total Encode+Decode delay = ENCDELAY + 528 + 1\n */\n\n/* \n * ENCDELAY  The encoder delay.  \n *\n * Minimum allowed is MDCTDELAY (see below)\n *  \n * The first 96 samples will be attenuated, so using a value less than 96\n * will result in corrupt data for the first 96-ENCDELAY samples.\n *\n * suggested: 576\n * set to 1160 to sync with FhG.\n */\n\n#define ENCDELAY      576\n\n\n\n/*\n * make sure there is at least one complete frame after the\n * last frame containing real data\n *\n * Using a value of 288 would be sufficient for a \n * a very sophisticated decoder that can decode granule-by-granule instead\n * of frame by frame.  But lets not assume this, and assume the decoder  \n * will not decode frame N unless it also has data for frame N+1\n *\n */\n/*#define POSTDELAY   288*/\n#define POSTDELAY   1152\n\n\n\n/* \n * delay of the MDCT used in mdct.c\n * original ISO routines had a delay of 528!  \n * Takehiro's routines: \n */\n\n#define MDCTDELAY     48\n#define FFTOFFSET     (224+MDCTDELAY)\n\n/*\n * Most decoders, including the one we use, have a delay of 528 samples.  \n */\n\n#define DECDELAY      528\n\n\n/* number of subbands */\n#define SBLIMIT       32\n\n/* parition bands bands */\n#define CBANDS        64\n\n/* number of critical bands/scale factor bands where masking is computed*/\n#define SBPSY_l       21\n#define SBPSY_s       12\n\n/* total number of scalefactor bands encoded */\n#define SBMAX_l       22\n#define SBMAX_s       13\n#define PSFB21         6\n#define PSFB12         6\n\n\n\n/* FFT sizes */\n#define BLKSIZE       1024\n#define HBLKSIZE      (BLKSIZE/2 + 1)\n#define BLKSIZE_s     256\n#define HBLKSIZE_s    (BLKSIZE_s/2 + 1)\n\n\n/* #define switch_pe        1800 */\n#define NORM_TYPE     0\n#define START_TYPE    1\n#define SHORT_TYPE    2\n#define STOP_TYPE     3\n\n/* \n * Mode Extention:\n * When we are in stereo mode, there are 4 possible methods to store these\n * two channels. The stereo modes -m? are using a subset of them.\n *\n *  -ms: MPG_MD_LR_LR\n *  -mj: MPG_MD_LR_LR and MPG_MD_MS_LR\n *  -mf: MPG_MD_MS_LR\n *  -mi: all\n */\n#if 0\n#define MPG_MD_LR_LR  0\n#define MPG_MD_LR_I   1\n#define MPG_MD_MS_LR  2\n#define MPG_MD_MS_I   3\n#endif\nenum MPEGChannelMode\n{   MPG_MD_LR_LR = 0\n,   MPG_MD_LR_I  = 1\n,   MPG_MD_MS_LR = 2\n,   MPG_MD_MS_I  = 3\n};\n\n#ifndef lame_internal_flags_defined\n#define lame_internal_flags_defined\nstruct lame_internal_flags;\ntypedef struct lame_internal_flags lame_internal_flags;\n#endif\n\nint     lame_encode_mp3_frame(lame_internal_flags * gfc,\n                              sample_t const *inbuf_l,\n                              sample_t const *inbuf_r, unsigned char *mp3buf, int mp3buf_size);\n\n#endif /* LAME_ENCODER_H */\n"
  },
  {
    "path": "app/jni/libmp3lame/fft.c",
    "content": "/*\n** FFT and FHT routines\n**  Copyright 1988, 1993; Ron Mayer\n**      Copyright (c) 1999-2000 Takehiro Tominaga\n**\n**  fht(fz,n);\n**      Does a hartley transform of \"n\" points in the array \"fz\".\n**\n** NOTE: This routine uses at least 2 patented algorithms, and may be\n**       under the restrictions of a bunch of different organizations.\n**       Although I wrote it completely myself; it is kind of a derivative\n**       of a routine I once authored and released under the GPL, so it\n**       may fall under the free software foundation's restrictions;\n**       it was worked on as a Stanford Univ project, so they claim\n**       some rights to it; it was further optimized at work here, so\n**       I think this company claims parts of it.  The patents are\n**       held by R. Bracewell (the FHT algorithm) and O. Buneman (the\n**       trig generator), both at Stanford Univ.\n**       If it were up to me, I'd say go do whatever you want with it;\n**       but it would be polite to give credit to the following people\n**       if you use this anywhere:\n**           Euler     - probable inventor of the fourier transform.\n**           Gauss     - probable inventor of the FFT.\n**           Hartley   - probable inventor of the hartley transform.\n**           Buneman   - for a really cool trig generator\n**           Mayer(me) - for authoring this particular version and\n**                       including all the optimizations in one package.\n**       Thanks,\n**       Ron Mayer; mayer@acuson.com\n** and added some optimization by\n**           Mather    - idea of using lookup table\n**           Takehiro  - some dirty hack for speed up\n*/\n\n/* $Id: fft.c,v 1.38 2009/04/20 21:48:00 robert Exp $ */\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"fft.h\"\n\n#include \"vector/lame_intrin.h\"\n\n\n\n#define TRI_SIZE (5-1)  /* 1024 =  4**5 */\n\n/* fft.c    */\nstatic FLOAT window[BLKSIZE], window_s[BLKSIZE_s / 2];\n\nstatic const FLOAT costab[TRI_SIZE * 2] = {\n    9.238795325112867e-01, 3.826834323650898e-01,\n    9.951847266721969e-01, 9.801714032956060e-02,\n    9.996988186962042e-01, 2.454122852291229e-02,\n    9.999811752826011e-01, 6.135884649154475e-03\n};\n\nstatic void\nfht(FLOAT * fz, int n)\n{\n    const FLOAT *tri = costab;\n    int     k4;\n    FLOAT  *fi, *gi;\n    FLOAT const *fn;\n\n    n <<= 1;            /* to get BLKSIZE, because of 3DNow! ASM routine */\n    fn = fz + n;\n    k4 = 4;\n    do {\n        FLOAT   s1, c1;\n        int     i, k1, k2, k3, kx;\n        kx = k4 >> 1;\n        k1 = k4;\n        k2 = k4 << 1;\n        k3 = k2 + k1;\n        k4 = k2 << 1;\n        fi = fz;\n        gi = fi + kx;\n        do {\n            FLOAT   f0, f1, f2, f3;\n            f1 = fi[0] - fi[k1];\n            f0 = fi[0] + fi[k1];\n            f3 = fi[k2] - fi[k3];\n            f2 = fi[k2] + fi[k3];\n            fi[k2] = f0 - f2;\n            fi[0] = f0 + f2;\n            fi[k3] = f1 - f3;\n            fi[k1] = f1 + f3;\n            f1 = gi[0] - gi[k1];\n            f0 = gi[0] + gi[k1];\n            f3 = SQRT2 * gi[k3];\n            f2 = SQRT2 * gi[k2];\n            gi[k2] = f0 - f2;\n            gi[0] = f0 + f2;\n            gi[k3] = f1 - f3;\n            gi[k1] = f1 + f3;\n            gi += k4;\n            fi += k4;\n        } while (fi < fn);\n        c1 = tri[0];\n        s1 = tri[1];\n        for (i = 1; i < kx; i++) {\n            FLOAT   c2, s2;\n            c2 = 1 - (2 * s1) * s1;\n            s2 = (2 * s1) * c1;\n            fi = fz + i;\n            gi = fz + k1 - i;\n            do {\n                FLOAT   a, b, g0, f0, f1, g1, f2, g2, f3, g3;\n                b = s2 * fi[k1] - c2 * gi[k1];\n                a = c2 * fi[k1] + s2 * gi[k1];\n                f1 = fi[0] - a;\n                f0 = fi[0] + a;\n                g1 = gi[0] - b;\n                g0 = gi[0] + b;\n                b = s2 * fi[k3] - c2 * gi[k3];\n                a = c2 * fi[k3] + s2 * gi[k3];\n                f3 = fi[k2] - a;\n                f2 = fi[k2] + a;\n                g3 = gi[k2] - b;\n                g2 = gi[k2] + b;\n                b = s1 * f2 - c1 * g3;\n                a = c1 * f2 + s1 * g3;\n                fi[k2] = f0 - a;\n                fi[0] = f0 + a;\n                gi[k3] = g1 - b;\n                gi[k1] = g1 + b;\n                b = c1 * g2 - s1 * f3;\n                a = s1 * g2 + c1 * f3;\n                gi[k2] = g0 - a;\n                gi[0] = g0 + a;\n                fi[k3] = f1 - b;\n                fi[k1] = f1 + b;\n                gi += k4;\n                fi += k4;\n            } while (fi < fn);\n            c2 = c1;\n            c1 = c2 * tri[0] - s1 * tri[1];\n            s1 = c2 * tri[1] + s1 * tri[0];\n        }\n        tri += 2;\n    } while (k4 < n);\n}\n\n\nstatic const unsigned char rv_tbl[] = {\n    0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,\n    0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,\n    0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,\n    0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,\n    0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,\n    0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,\n    0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,\n    0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,\n    0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,\n    0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,\n    0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,\n    0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,\n    0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,\n    0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,\n    0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,\n    0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe\n};\n\n#define ch01(index)  (buffer[chn][index])\n\n#define ml00(f) (window[i        ] * f(i))\n#define ml10(f) (window[i + 0x200] * f(i + 0x200))\n#define ml20(f) (window[i + 0x100] * f(i + 0x100))\n#define ml30(f) (window[i + 0x300] * f(i + 0x300))\n\n#define ml01(f) (window[i + 0x001] * f(i + 0x001))\n#define ml11(f) (window[i + 0x201] * f(i + 0x201))\n#define ml21(f) (window[i + 0x101] * f(i + 0x101))\n#define ml31(f) (window[i + 0x301] * f(i + 0x301))\n\n#define ms00(f) (window_s[i       ] * f(i + k))\n#define ms10(f) (window_s[0x7f - i] * f(i + k + 0x80))\n#define ms20(f) (window_s[i + 0x40] * f(i + k + 0x40))\n#define ms30(f) (window_s[0x3f - i] * f(i + k + 0xc0))\n\n#define ms01(f) (window_s[i + 0x01] * f(i + k + 0x01))\n#define ms11(f) (window_s[0x7e - i] * f(i + k + 0x81))\n#define ms21(f) (window_s[i + 0x41] * f(i + k + 0x41))\n#define ms31(f) (window_s[0x3e - i] * f(i + k + 0xc1))\n\n\nvoid\nfft_short(lame_internal_flags const *const gfc,\n          FLOAT x_real[3][BLKSIZE_s], int chn, const sample_t *const buffer[2])\n{\n    int     i;\n    int     j;\n    int     b;\n\n    for (b = 0; b < 3; b++) {\n        FLOAT  *x = &x_real[b][BLKSIZE_s / 2];\n        short const k = (576 / 3) * (b + 1);\n        j = BLKSIZE_s / 8 - 1;\n        do {\n            FLOAT   f0, f1, f2, f3, w;\n\n            i = rv_tbl[j << 2];\n\n            f0 = ms00(ch01);\n            w = ms10(ch01);\n            f1 = f0 - w;\n            f0 = f0 + w;\n            f2 = ms20(ch01);\n            w = ms30(ch01);\n            f3 = f2 - w;\n            f2 = f2 + w;\n\n            x -= 4;\n            x[0] = f0 + f2;\n            x[2] = f0 - f2;\n            x[1] = f1 + f3;\n            x[3] = f1 - f3;\n\n            f0 = ms01(ch01);\n            w = ms11(ch01);\n            f1 = f0 - w;\n            f0 = f0 + w;\n            f2 = ms21(ch01);\n            w = ms31(ch01);\n            f3 = f2 - w;\n            f2 = f2 + w;\n\n            x[BLKSIZE_s / 2 + 0] = f0 + f2;\n            x[BLKSIZE_s / 2 + 2] = f0 - f2;\n            x[BLKSIZE_s / 2 + 1] = f1 + f3;\n            x[BLKSIZE_s / 2 + 3] = f1 - f3;\n        } while (--j >= 0);\n\n        gfc->fft_fht(x, BLKSIZE_s / 2);\n        /* BLKSIZE_s/2 because of 3DNow! ASM routine */\n    }\n}\n\nvoid\nfft_long(lame_internal_flags const *const gfc,\n         FLOAT x[BLKSIZE], int chn, const sample_t *const buffer[2])\n{\n    int     i;\n    int     jj = BLKSIZE / 8 - 1;\n    x += BLKSIZE / 2;\n\n    do {\n        FLOAT   f0, f1, f2, f3, w;\n\n        i = rv_tbl[jj];\n        f0 = ml00(ch01);\n        w = ml10(ch01);\n        f1 = f0 - w;\n        f0 = f0 + w;\n        f2 = ml20(ch01);\n        w = ml30(ch01);\n        f3 = f2 - w;\n        f2 = f2 + w;\n\n        x -= 4;\n        x[0] = f0 + f2;\n        x[2] = f0 - f2;\n        x[1] = f1 + f3;\n        x[3] = f1 - f3;\n\n        f0 = ml01(ch01);\n        w = ml11(ch01);\n        f1 = f0 - w;\n        f0 = f0 + w;\n        f2 = ml21(ch01);\n        w = ml31(ch01);\n        f3 = f2 - w;\n        f2 = f2 + w;\n\n        x[BLKSIZE / 2 + 0] = f0 + f2;\n        x[BLKSIZE / 2 + 2] = f0 - f2;\n        x[BLKSIZE / 2 + 1] = f1 + f3;\n        x[BLKSIZE / 2 + 3] = f1 - f3;\n    } while (--jj >= 0);\n\n    gfc->fft_fht(x, BLKSIZE / 2);\n    /* BLKSIZE/2 because of 3DNow! ASM routine */\n}\n\n#ifdef HAVE_NASM\nextern void fht_3DN(FLOAT * fz, int n);\nextern void fht_SSE(FLOAT * fz, int n);\n#endif\n\nvoid\ninit_fft(lame_internal_flags * const gfc)\n{\n    int     i;\n\n    /* The type of window used here will make no real difference, but */\n    /* in the interest of merging nspsytune stuff - switch to blackman window */\n    for (i = 0; i < BLKSIZE; i++)\n        /* blackman window */\n        window[i] = 0.42 - 0.5 * cos(2 * PI * (i + .5) / BLKSIZE) +\n            0.08 * cos(4 * PI * (i + .5) / BLKSIZE);\n\n    for (i = 0; i < BLKSIZE_s / 2; i++)\n        window_s[i] = 0.5 * (1.0 - cos(2.0 * PI * (i + 0.5) / BLKSIZE_s));\n\n    gfc->fft_fht = fht;\n#ifdef HAVE_NASM\n    if (gfc->CPU_features.AMD_3DNow) {\n        gfc->fft_fht = fht_3DN;\n    }\n    else if (gfc->CPU_features.SSE) {\n        gfc->fft_fht = fht_SSE;\n    }\n    else {\n        gfc->fft_fht = fht;\n    }\n#else\n#ifdef HAVE_XMMINTRIN_H\n#ifdef MIN_ARCH_SSE\n    gfc->fft_fht = fht_SSE2;\n#endif\n#endif\n#endif\n}\n"
  },
  {
    "path": "app/jni/libmp3lame/fft.h",
    "content": "/*\n *\tFast Fourier Transform include file\n *\n *\tCopyright (c) 2000 Mark Taylor\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_FFT_H\n#define LAME_FFT_H\n\nvoid    fft_long(lame_internal_flags const *const gfc, FLOAT x_real[BLKSIZE],\n                 int chn, const sample_t *const data[2]);\n\nvoid    fft_short(lame_internal_flags const *const gfc, FLOAT x_real[3][BLKSIZE_s],\n                  int chn, const sample_t *const data[2]);\n\nvoid    init_fft(lame_internal_flags * const gfc);\n\n#endif\n\n/* End of fft.h */\n"
  },
  {
    "path": "app/jni/libmp3lame/gain_analysis.c",
    "content": "/*\n *  ReplayGainAnalysis - analyzes input samples and give the recommended dB change\n *  Copyright (C) 2001 David Robinson and Glen Sawyer\n *  Improvements and optimizations added by Frank Klemm, and by Marcel Muller \n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation; either\n *  version 2.1 of the License, or (at your option) any later version.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\n *  concept and filter values by David Robinson (David@Robinson.org)\n *    -- blame him if you think the idea is flawed\n *  original coding by Glen Sawyer (mp3gain@hotmail.com)\n *    -- blame him if you think this runs too slowly, or the coding is otherwise flawed\n *\n *  lots of code improvements by Frank Klemm ( http://www.uni-jena.de/~pfk/mpp/ )\n *    -- credit him for all the _good_ programming ;)\n *\n *\n *  For an explanation of the concepts and the basic algorithms involved, go to:\n *    http://www.replaygain.org/\n */\n\n/*\n *  Here's the deal. Call\n *\n *    InitGainAnalysis ( long samplefreq );\n *\n *  to initialize everything. Call\n *\n *    AnalyzeSamples ( const Float_t*  left_samples,\n *                     const Float_t*  right_samples,\n *                     size_t          num_samples,\n *                     int             num_channels );\n *\n *  as many times as you want, with as many or as few samples as you want.\n *  If mono, pass the sample buffer in through left_samples, leave\n *  right_samples NULL, and make sure num_channels = 1.\n *\n *    GetTitleGain()\n *\n *  will return the recommended dB level change for all samples analyzed\n *  SINCE THE LAST TIME you called GetTitleGain() OR InitGainAnalysis().\n *\n *    GetAlbumGain()\n *\n *  will return the recommended dB level change for all samples analyzed\n *  since InitGainAnalysis() was called and finalized with GetTitleGain().\n *\n *  Pseudo-code to process an album:\n *\n *    Float_t       l_samples [4096];\n *    Float_t       r_samples [4096];\n *    size_t        num_samples;\n *    unsigned int  num_songs;\n *    unsigned int  i;\n *\n *    InitGainAnalysis ( 44100 );\n *    for ( i = 1; i <= num_songs; i++ ) {\n *        while ( ( num_samples = getSongSamples ( song[i], left_samples, right_samples ) ) > 0 )\n *            AnalyzeSamples ( left_samples, right_samples, num_samples, 2 );\n *        fprintf (\"Recommended dB change for song %2d: %+6.2f dB\\n\", i, GetTitleGain() );\n *    }\n *    fprintf (\"Recommended dB change for whole album: %+6.2f dB\\n\", GetAlbumGain() );\n */\n\n/*\n *  So here's the main source of potential code confusion:\n *\n *  The filters applied to the incoming samples are IIR filters,\n *  meaning they rely on up to <filter order> number of previous samples\n *  AND up to <filter order> number of previous filtered samples.\n *\n *  I set up the AnalyzeSamples routine to minimize memory usage and interface\n *  complexity. The speed isn't compromised too much (I don't think), but the\n *  internal complexity is higher than it should be for such a relatively\n *  simple routine.\n *\n *  Optimization/clarity suggestions are welcome.\n */\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <strings.h>\n\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"gain_analysis.h\"\n\n/* for each filter: */\n/* [0] 48 kHz, [1] 44.1 kHz, [2] 32 kHz, [3] 24 kHz, [4] 22050 Hz, [5] 16 kHz, [6] 12 kHz, [7] is 11025 Hz, [8] 8 kHz */\n\n#ifdef WIN32\n#pragma warning ( disable : 4305 )\n#endif\n\n/*lint -save -e736 loss of precision */\nstatic const Float_t ABYule[9][2 * YULE_ORDER + 1] = {\n    {0.03857599435200, -3.84664617118067, -0.02160367184185, 7.81501653005538, -0.00123395316851,\n     -11.34170355132042, -0.00009291677959, 13.05504219327545, -0.01655260341619,\n     -12.28759895145294, 0.02161526843274, 9.48293806319790, -0.02074045215285, -5.87257861775999,\n     0.00594298065125, 2.75465861874613, 0.00306428023191, -0.86984376593551, 0.00012025322027,\n     0.13919314567432, 0.00288463683916},\n    {0.05418656406430, -3.47845948550071, -0.02911007808948, 6.36317777566148, -0.00848709379851,\n     -8.54751527471874, -0.00851165645469, 9.47693607801280, -0.00834990904936, -8.81498681370155,\n     0.02245293253339, 6.85401540936998, -0.02596338512915, -4.39470996079559, 0.01624864962975,\n     2.19611684890774, -0.00240879051584, -0.75104302451432, 0.00674613682247, 0.13149317958808,\n     -0.00187763777362},\n    {0.15457299681924, -2.37898834973084, -0.09331049056315, 2.84868151156327, -0.06247880153653,\n     -2.64577170229825, 0.02163541888798, 2.23697657451713, -0.05588393329856, -1.67148153367602,\n     0.04781476674921, 1.00595954808547, 0.00222312597743, -0.45953458054983, 0.03174092540049,\n     0.16378164858596, -0.01390589421898, -0.05032077717131, 0.00651420667831, 0.02347897407020,\n     -0.00881362733839},\n    {0.30296907319327, -1.61273165137247, -0.22613988682123, 1.07977492259970, -0.08587323730772,\n     -0.25656257754070, 0.03282930172664, -0.16276719120440, -0.00915702933434, -0.22638893773906,\n     -0.02364141202522, 0.39120800788284, -0.00584456039913, -0.22138138954925, 0.06276101321749,\n     0.04500235387352, -0.00000828086748, 0.02005851806501, 0.00205861885564, 0.00302439095741,\n     -0.02950134983287},\n    {0.33642304856132, -1.49858979367799, -0.25572241425570, 0.87350271418188, -0.11828570177555,\n     0.12205022308084, 0.11921148675203, -0.80774944671438, -0.07834489609479, 0.47854794562326,\n     -0.00469977914380, -0.12453458140019, -0.00589500224440, -0.04067510197014, 0.05724228140351,\n     0.08333755284107, 0.00832043980773, -0.04237348025746, -0.01635381384540, 0.02977207319925,\n     -0.01760176568150},\n    {0.44915256608450, -0.62820619233671, -0.14351757464547, 0.29661783706366, -0.22784394429749,\n     -0.37256372942400, -0.01419140100551, 0.00213767857124, 0.04078262797139, -0.42029820170918,\n     -0.12398163381748, 0.22199650564824, 0.04097565135648, 0.00613424350682, 0.10478503600251,\n     0.06747620744683, -0.01863887810927, 0.05784820375801, -0.03193428438915, 0.03222754072173,\n     0.00541907748707},\n    {0.56619470757641, -1.04800335126349, -0.75464456939302, 0.29156311971249, 0.16242137742230,\n     -0.26806001042947, 0.16744243493672, 0.00819999645858, -0.18901604199609, 0.45054734505008,\n     0.30931782841830, -0.33032403314006, -0.27562961986224, 0.06739368333110, 0.00647310677246,\n     -0.04784254229033, 0.08647503780351, 0.01639907836189, -0.03788984554840, 0.01807364323573,\n     -0.00588215443421},\n    {0.58100494960553, -0.51035327095184, -0.53174909058578, -0.31863563325245, -0.14289799034253,\n     -0.20256413484477, 0.17520704835522, 0.14728154134330, 0.02377945217615, 0.38952639978999,\n     0.15558449135573, -0.23313271880868, -0.25344790059353, -0.05246019024463, 0.01628462406333,\n     -0.02505961724053, 0.06920467763959, 0.02442357316099, -0.03721611395801, 0.01818801111503,\n     -0.00749618797172},\n    {0.53648789255105, -0.25049871956020, -0.42163034350696, -0.43193942311114, -0.00275953611929,\n     -0.03424681017675, 0.04267842219415, -0.04678328784242, -0.10214864179676, 0.26408300200955,\n     0.14590772289388, 0.15113130533216, -0.02459864859345, -0.17556493366449, -0.11202315195388,\n     -0.18823009262115, -0.04060034127000, 0.05477720428674, 0.04788665548180, 0.04704409688120,\n     -0.02217936801134}\n};\n\nstatic const Float_t ABButter[9][2 * BUTTER_ORDER + 1] = {\n    {0.98621192462708, -1.97223372919527, -1.97242384925416, 0.97261396931306, 0.98621192462708},\n    {0.98500175787242, -1.96977855582618, -1.97000351574484, 0.97022847566350, 0.98500175787242},\n    {0.97938932735214, -1.95835380975398, -1.95877865470428, 0.95920349965459, 0.97938932735214},\n    {0.97531843204928, -1.95002759149878, -1.95063686409857, 0.95124613669835, 0.97531843204928},\n    {0.97316523498161, -1.94561023566527, -1.94633046996323, 0.94705070426118, 0.97316523498161},\n    {0.96454515552826, -1.92783286977036, -1.92909031105652, 0.93034775234268, 0.96454515552826},\n    {0.96009142950541, -1.91858953033784, -1.92018285901082, 0.92177618768381, 0.96009142950541},\n    {0.95856916599601, -1.91542108074780, -1.91713833199203, 0.91885558323625, 0.95856916599601},\n    {0.94597685600279, -1.88903307939452, -1.89195371200558, 0.89487434461664, 0.94597685600279}\n};\n\n/*lint -restore */\n\n#ifdef WIN32\n#pragma warning ( default : 4305 )\n#endif\n\n/* When calling this procedure, make sure that ip[-order] and op[-order] point to real data! */\n\nstatic void\nfilterYule(const Float_t * input, Float_t * output, size_t nSamples, const Float_t * const kernel)\n{\n    /*register double  y; */\n\n    while (nSamples--) {\n        *output = 1e-10 /* 1e-10 is a hack to avoid slowdown because of denormals */\n            + input[0] * kernel[0]\n            - output[-1] * kernel[1]\n            + input[-1] * kernel[2]\n            - output[-2] * kernel[3]\n            + input[-2] * kernel[4]\n            - output[-3] * kernel[5]\n            + input[-3] * kernel[6]\n            - output[-4] * kernel[7]\n            + input[-4] * kernel[8]\n            - output[-5] * kernel[9]\n            + input[-5] * kernel[10]\n            - output[-6] * kernel[11]\n            + input[-6] * kernel[12]\n            - output[-7] * kernel[13]\n            + input[-7] * kernel[14]\n            - output[-8] * kernel[15]\n            + input[-8] * kernel[16]\n            - output[-9] * kernel[17]\n            + input[-9] * kernel[18]\n            - output[-10] * kernel[19]\n            + input[-10] * kernel[20];\n        ++output;\n        ++input;\n        /* *output++ = (Float_t)y; */\n    }\n}\n\nstatic void\nfilterButter(const Float_t * input, Float_t * output, size_t nSamples, const Float_t * const kernel)\n{                       /*register double  y; */\n\n    while (nSamples--) {\n        *output = input[0] * kernel[0]\n            - output[-1] * kernel[1]\n            + input[-1] * kernel[2]\n            - output[-2] * kernel[3]\n            + input[-2] * kernel[4];\n        ++output;\n        ++input;\n        /* *output++ = (Float_t)y; */\n    }\n}\n\n\n\nstatic int ResetSampleFrequency(replaygain_t * rgData, long samplefreq);\n\n/* returns a INIT_GAIN_ANALYSIS_OK if successful, INIT_GAIN_ANALYSIS_ERROR if not */\n\nint\nResetSampleFrequency(replaygain_t * rgData, long samplefreq)\n{\n    int     i;\n\n    /* zero out initial values */\n    for (i = 0; i < MAX_ORDER; i++)\n        rgData->linprebuf[i] = rgData->lstepbuf[i]\n            = rgData->loutbuf[i]\n            = rgData->rinprebuf[i]\n            = rgData->rstepbuf[i]\n            = rgData->routbuf[i] = 0.;\n\n    switch ((int) (samplefreq)) {\n    case 48000:\n        rgData->freqindex = 0;\n        break;\n    case 44100:\n        rgData->freqindex = 1;\n        break;\n    case 32000:\n        rgData->freqindex = 2;\n        break;\n    case 24000:\n        rgData->freqindex = 3;\n        break;\n    case 22050:\n        rgData->freqindex = 4;\n        break;\n    case 16000:\n        rgData->freqindex = 5;\n        break;\n    case 12000:\n        rgData->freqindex = 6;\n        break;\n    case 11025:\n        rgData->freqindex = 7;\n        break;\n    case 8000:\n        rgData->freqindex = 8;\n        break;\n    default:\n        return INIT_GAIN_ANALYSIS_ERROR;\n    }\n\n    rgData->sampleWindow =\n        (samplefreq * RMS_WINDOW_TIME_NUMERATOR + RMS_WINDOW_TIME_DENOMINATOR -\n         1) / RMS_WINDOW_TIME_DENOMINATOR;\n\n    rgData->lsum = 0.;\n    rgData->rsum = 0.;\n    rgData->totsamp = 0;\n\n    memset(rgData->A, 0, sizeof(rgData->A));\n\n    return INIT_GAIN_ANALYSIS_OK;\n}\n\nint\nInitGainAnalysis(replaygain_t * rgData, long samplefreq)\n{\n    if (ResetSampleFrequency(rgData, samplefreq) != INIT_GAIN_ANALYSIS_OK) {\n        return INIT_GAIN_ANALYSIS_ERROR;\n    }\n\n    rgData->linpre = rgData->linprebuf + MAX_ORDER;\n    rgData->rinpre = rgData->rinprebuf + MAX_ORDER;\n    rgData->lstep = rgData->lstepbuf + MAX_ORDER;\n    rgData->rstep = rgData->rstepbuf + MAX_ORDER;\n    rgData->lout = rgData->loutbuf + MAX_ORDER;\n    rgData->rout = rgData->routbuf + MAX_ORDER;\n\n    memset(rgData->B, 0, sizeof(rgData->B));\n\n    return INIT_GAIN_ANALYSIS_OK;\n}\n\n/* returns GAIN_ANALYSIS_OK if successful, GAIN_ANALYSIS_ERROR if not */\n\nstatic inline double\nfsqr(const double d)\n{\n    return d * d;\n}\n\nint\nAnalyzeSamples(replaygain_t * rgData, const Float_t * left_samples, const Float_t * right_samples,\n               size_t num_samples, int num_channels)\n{\n    const Float_t *curleft;\n    const Float_t *curright;\n    long    batchsamples;\n    long    cursamples;\n    long    cursamplepos;\n    int     i;\n\n    if (num_samples == 0)\n        return GAIN_ANALYSIS_OK;\n\n    cursamplepos = 0;\n    batchsamples = (long) num_samples;\n\n    switch (num_channels) {\n    case 1:\n        right_samples = left_samples;\n        break;\n    case 2:\n        break;\n    default:\n        return GAIN_ANALYSIS_ERROR;\n    }\n\n    if (num_samples < MAX_ORDER) {\n        memcpy(rgData->linprebuf + MAX_ORDER, left_samples, num_samples * sizeof(Float_t));\n        memcpy(rgData->rinprebuf + MAX_ORDER, right_samples, num_samples * sizeof(Float_t));\n    }\n    else {\n        memcpy(rgData->linprebuf + MAX_ORDER, left_samples, MAX_ORDER * sizeof(Float_t));\n        memcpy(rgData->rinprebuf + MAX_ORDER, right_samples, MAX_ORDER * sizeof(Float_t));\n    }\n\n    while (batchsamples > 0) {\n        cursamples = batchsamples > rgData->sampleWindow - rgData->totsamp ?\n            rgData->sampleWindow - rgData->totsamp : batchsamples;\n        if (cursamplepos < MAX_ORDER) {\n            curleft = rgData->linpre + cursamplepos;\n            curright = rgData->rinpre + cursamplepos;\n            if (cursamples > MAX_ORDER - cursamplepos)\n                cursamples = MAX_ORDER - cursamplepos;\n        }\n        else {\n            curleft = left_samples + cursamplepos;\n            curright = right_samples + cursamplepos;\n        }\n\n        YULE_FILTER(curleft, rgData->lstep + rgData->totsamp, cursamples,\n                    ABYule[rgData->freqindex]);\n        YULE_FILTER(curright, rgData->rstep + rgData->totsamp, cursamples,\n                    ABYule[rgData->freqindex]);\n\n        BUTTER_FILTER(rgData->lstep + rgData->totsamp, rgData->lout + rgData->totsamp, cursamples,\n                      ABButter[rgData->freqindex]);\n        BUTTER_FILTER(rgData->rstep + rgData->totsamp, rgData->rout + rgData->totsamp, cursamples,\n                      ABButter[rgData->freqindex]);\n\n        curleft = rgData->lout + rgData->totsamp; /* Get the squared values */\n        curright = rgData->rout + rgData->totsamp;\n\n        i = cursamples % 8;\n        while (i--) {\n            rgData->lsum += fsqr(*curleft++);\n            rgData->rsum += fsqr(*curright++);\n        }\n        i = cursamples / 8;\n        while (i--) {\n            rgData->lsum += fsqr(curleft[0])\n                + fsqr(curleft[1])\n                + fsqr(curleft[2])\n                + fsqr(curleft[3])\n                + fsqr(curleft[4])\n                + fsqr(curleft[5])\n                + fsqr(curleft[6])\n                + fsqr(curleft[7]);\n            curleft += 8;\n            rgData->rsum += fsqr(curright[0])\n                + fsqr(curright[1])\n                + fsqr(curright[2])\n                + fsqr(curright[3])\n                + fsqr(curright[4])\n                + fsqr(curright[5])\n                + fsqr(curright[6])\n                + fsqr(curright[7]);\n            curright += 8;\n        }\n\n        batchsamples -= cursamples;\n        cursamplepos += cursamples;\n        rgData->totsamp += cursamples;\n        if (rgData->totsamp == rgData->sampleWindow) { /* Get the Root Mean Square (RMS) for this set of samples */\n            double const val =\n                STEPS_per_dB * 10. * log10((rgData->lsum + rgData->rsum) / rgData->totsamp * 0.5 +\n                                           1.e-37);\n            size_t  ival = (val <= 0) ? 0 : (size_t) val;\n            if (ival >= sizeof(rgData->A) / sizeof(*(rgData->A)))\n                ival = sizeof(rgData->A) / sizeof(*(rgData->A)) - 1;\n            rgData->A[ival]++;\n            rgData->lsum = rgData->rsum = 0.;\n            memmove(rgData->loutbuf, rgData->loutbuf + rgData->totsamp,\n                    MAX_ORDER * sizeof(Float_t));\n            memmove(rgData->routbuf, rgData->routbuf + rgData->totsamp,\n                    MAX_ORDER * sizeof(Float_t));\n            memmove(rgData->lstepbuf, rgData->lstepbuf + rgData->totsamp,\n                    MAX_ORDER * sizeof(Float_t));\n            memmove(rgData->rstepbuf, rgData->rstepbuf + rgData->totsamp,\n                    MAX_ORDER * sizeof(Float_t));\n            rgData->totsamp = 0;\n        }\n        if (rgData->totsamp > rgData->sampleWindow) /* somehow I really screwed up: Error in programming! Contact author about totsamp > sampleWindow */\n            return GAIN_ANALYSIS_ERROR;\n    }\n    if (num_samples < MAX_ORDER) {\n        memmove(rgData->linprebuf, rgData->linprebuf + num_samples,\n                (MAX_ORDER - num_samples) * sizeof(Float_t));\n        memmove(rgData->rinprebuf, rgData->rinprebuf + num_samples,\n                (MAX_ORDER - num_samples) * sizeof(Float_t));\n        memcpy(rgData->linprebuf + MAX_ORDER - num_samples, left_samples,\n               num_samples * sizeof(Float_t));\n        memcpy(rgData->rinprebuf + MAX_ORDER - num_samples, right_samples,\n               num_samples * sizeof(Float_t));\n    }\n    else {\n        memcpy(rgData->linprebuf, left_samples + num_samples - MAX_ORDER,\n               MAX_ORDER * sizeof(Float_t));\n        memcpy(rgData->rinprebuf, right_samples + num_samples - MAX_ORDER,\n               MAX_ORDER * sizeof(Float_t));\n    }\n\n    return GAIN_ANALYSIS_OK;\n}\n\n\nstatic  Float_t\nanalyzeResult(uint32_t const *Array, size_t len)\n{\n    uint32_t elems;\n    uint32_t upper;\n    uint32_t sum;\n    size_t  i;\n\n    elems = 0;\n    for (i = 0; i < len; i++)\n        elems += Array[i];\n    if (elems == 0)\n        return GAIN_NOT_ENOUGH_SAMPLES;\n\n    upper = (uint32_t) ceil(elems * (1. - RMS_PERCENTILE));\n    sum = 0;\n    for (i = len; i-- > 0;) {\n        sum += Array[i];\n        if (sum >= upper) {\n            break;\n        }\n    }\n\n    return (Float_t) ((Float_t) PINK_REF - (Float_t) i / (Float_t) STEPS_per_dB);\n}\n\n\nFloat_t\nGetTitleGain(replaygain_t * rgData)\n{\n    Float_t retval;\n    unsigned int i;\n\n    retval = analyzeResult(rgData->A, sizeof(rgData->A) / sizeof(*(rgData->A)));\n\n    for (i = 0; i < sizeof(rgData->A) / sizeof(*(rgData->A)); i++) {\n        rgData->B[i] += rgData->A[i];\n        rgData->A[i] = 0;\n    }\n\n    for (i = 0; i < MAX_ORDER; i++)\n        rgData->linprebuf[i] = rgData->lstepbuf[i]\n            = rgData->loutbuf[i]\n            = rgData->rinprebuf[i]\n            = rgData->rstepbuf[i]\n            = rgData->routbuf[i] = 0.f;\n\n    rgData->totsamp = 0;\n    rgData->lsum = rgData->rsum = 0.;\n    return retval;\n}\n\n#if 0\nstatic Float_t GetAlbumGain(replaygain_t const* rgData);\n\nFloat_t\nGetAlbumGain(replaygain_t const* rgData)\n{\n    return analyzeResult(rgData->B, sizeof(rgData->B) / sizeof(*(rgData->B)));\n}\n#endif\n\n/* end of gain_analysis.c */\n"
  },
  {
    "path": "app/jni/libmp3lame/gain_analysis.h",
    "content": "/*\n *  ReplayGainAnalysis - analyzes input samples and give the recommended dB change\n *  Copyright (C) 2001 David Robinson and Glen Sawyer\n *\n *  This library is free software; you can redistribute it and/or\n *  modify it under the terms of the GNU Lesser General Public\n *  License as published by the Free Software Foundation; either\n *  version 2.1 of the License, or (at your option) any later version.\n *\n *  This library is distributed in the hope that it will be useful,\n *  but WITHOUT ANY WARRANTY; without even the implied warranty of\n *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n *  Lesser General Public License for more details.\n *\n *  You should have received a copy of the GNU Lesser General Public\n *  License along with this library; if not, write to the Free Software\n *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\n *  concept and filter values by David Robinson (David@Robinson.org)\n *    -- blame him if you think the idea is flawed\n *  coding by Glen Sawyer (mp3gain@hotmail.com) 735 W 255 N, Orem, UT 84057-4505 USA\n *    -- blame him if you think this runs too slowly, or the coding is otherwise flawed\n *\n *  For an explanation of the concepts and the basic algorithms involved, go to:\n *    http://www.replaygain.org/\n */\n\n#ifndef GAIN_ANALYSIS_H\n#define GAIN_ANALYSIS_H\n\n#ifdef HAVE_INTTYPES_H\n# include <inttypes.h>\n#else\n# ifdef HAVE_STDINT_H\n#  include <stdint.h>\n# endif\n#endif\n\n#ifdef __cplusplus\nextern  \"C\" {\n#endif\n\n\n    typedef sample_t Float_t; /* Type used for filtering */\n\n\n#define PINK_REF                64.82       /* 298640883795 */ /* calibration value for 89dB */\n\n\n#define YULE_ORDER         10\n#define BUTTER_ORDER        2\n#define YULE_FILTER     filterYule\n#define BUTTER_FILTER   filterButter\n#define RMS_PERCENTILE      0.95 /* percentile which is louder than the proposed level */\n#define MAX_SAMP_FREQ   48000L /* maximum allowed sample frequency [Hz] */\n#define RMS_WINDOW_TIME_NUMERATOR    1L\n#define RMS_WINDOW_TIME_DENOMINATOR 20L /* numerator / denominator = time slice size [s] */\n#define STEPS_per_dB      100 /* Table entries per dB */\n#define MAX_dB            120 /* Table entries for 0...MAX_dB (normal max. values are 70...80 dB) */\n\n    enum { GAIN_NOT_ENOUGH_SAMPLES = -24601, GAIN_ANALYSIS_ERROR = 0, GAIN_ANALYSIS_OK =\n            1, INIT_GAIN_ANALYSIS_ERROR = 0, INIT_GAIN_ANALYSIS_OK = 1\n    };\n\n    enum { MAX_ORDER = (BUTTER_ORDER > YULE_ORDER ? BUTTER_ORDER : YULE_ORDER)\n            , MAX_SAMPLES_PER_WINDOW = ((MAX_SAMP_FREQ * RMS_WINDOW_TIME_NUMERATOR) / RMS_WINDOW_TIME_DENOMINATOR + 1) /* max. Samples per Time slice */\n    };\n\n    struct replaygain_data {\n        Float_t linprebuf[MAX_ORDER * 2];\n        Float_t *linpre;     /* left input samples, with pre-buffer */\n        Float_t lstepbuf[MAX_SAMPLES_PER_WINDOW + MAX_ORDER];\n        Float_t *lstep;      /* left \"first step\" (i.e. post first filter) samples */\n        Float_t loutbuf[MAX_SAMPLES_PER_WINDOW + MAX_ORDER];\n        Float_t *lout;       /* left \"out\" (i.e. post second filter) samples */\n        Float_t rinprebuf[MAX_ORDER * 2];\n        Float_t *rinpre;     /* right input samples ... */\n        Float_t rstepbuf[MAX_SAMPLES_PER_WINDOW + MAX_ORDER];\n        Float_t *rstep;\n        Float_t routbuf[MAX_SAMPLES_PER_WINDOW + MAX_ORDER];\n        Float_t *rout;\n        long    sampleWindow; /* number of samples required to reach number of milliseconds required for RMS window */\n        long    totsamp;\n        double  lsum;\n        double  rsum;\n        int     freqindex;\n        int     first;\n        uint32_t A[STEPS_per_dB * MAX_dB];\n        uint32_t B[STEPS_per_dB * MAX_dB];\n\n    };\n#ifndef replaygain_data_defined\n#define replaygain_data_defined\n    typedef struct replaygain_data replaygain_t;\n#endif\n\n\n\n\n    int     InitGainAnalysis(replaygain_t * rgData, long samplefreq);\n    int     AnalyzeSamples(replaygain_t * rgData, const Float_t * left_samples,\n                           const Float_t * right_samples, size_t num_samples, int num_channels);\n    Float_t GetTitleGain(replaygain_t * rgData);\n\n\n#ifdef __cplusplus\n}\n#endif\n#endif                       /* GAIN_ANALYSIS_H */\n"
  },
  {
    "path": "app/jni/libmp3lame/id3tag.c",
    "content": "/*\n * id3tag.c -- Write ID3 version 1 and 2 tags.\n *\n * Copyright (C) 2000 Don Melton\n * Copyright (C) 2011-2012 Robert Hegemann\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\n\n/*\n * HISTORY: This source file is part of LAME (see http://www.mp3dev.org)\n * and was originally adapted by Conrad Sanderson <c.sanderson@me.gu.edu.au>\n * from mp3info by Ricardo Cerqueira <rmc@rccn.net> to write only ID3 version 1\n * tags.  Don Melton <don@blivet.com> COMPLETELY rewrote it to support version\n * 2 tags and be more conformant to other standards while remaining flexible.\n *\n * NOTE: See http://id3.org/ for more information about ID3 tag formats.\n */\n\n/* $Id: id3tag.c,v 1.75.2.2 2012/01/08 23:49:58 robert Exp $ */\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#ifdef STDC_HEADERS\n# include <stddef.h>\n# include <stdlib.h>\n# include <string.h>\n# include <ctype.h>\n#else\n# ifndef HAVE_STRCHR\n#  define strchr index\n#  define strrchr rindex\n# endif\nchar   *strchr(), *strrchr();\n# ifndef HAVE_MEMCPY\n#  define memcpy(d, s, n) bcopy ((s), (d), (n))\n# endif\n#endif\n\n\n#include <string.h>\n#include <malloc.h>\n#include <strings.h>\n#include <stdlib.h>\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"id3tag.h\"\n#include \"lame_global_flags.h\"\n#include \"util.h\"\n#include \"bitstream.h\"\n\n#define lame_calloc(TYPE, COUNT) ((TYPE*)calloc(COUNT, sizeof(TYPE)))\n\nstatic const char *const genre_names[] = {\n    /*\n     * NOTE: The spelling of these genre names is identical to those found in\n     * Winamp and mp3info.\n     */\n    \"Blues\", \"Classic Rock\", \"Country\", \"Dance\", \"Disco\", \"Funk\", \"Grunge\",\n    \"Hip-Hop\", \"Jazz\", \"Metal\", \"New Age\", \"Oldies\", \"Other\", \"Pop\", \"R&B\",\n    \"Rap\", \"Reggae\", \"Rock\", \"Techno\", \"Industrial\", \"Alternative\", \"Ska\",\n    \"Death Metal\", \"Pranks\", \"Soundtrack\", \"Euro-Techno\", \"Ambient\", \"Trip-Hop\",\n    \"Vocal\", \"Jazz+Funk\", \"Fusion\", \"Trance\", \"Classical\", \"Instrumental\",\n    \"Acid\", \"House\", \"Game\", \"Sound Clip\", \"Gospel\", \"Noise\", \"Alternative Rock\",\n    \"Bass\", \"Soul\", \"Punk\", \"Space\", \"Meditative\", \"Instrumental Pop\",\n    \"Instrumental Rock\", \"Ethnic\", \"Gothic\", \"Darkwave\", \"Techno-Industrial\",\n    \"Electronic\", \"Pop-Folk\", \"Eurodance\", \"Dream\", \"Southern Rock\", \"Comedy\",\n    \"Cult\", \"Gangsta\", \"Top 40\", \"Christian Rap\", \"Pop/Funk\", \"Jungle\",\n    \"Native US\", \"Cabaret\", \"New Wave\", \"Psychedelic\", \"Rave\",\n    \"Showtunes\", \"Trailer\", \"Lo-Fi\", \"Tribal\", \"Acid Punk\", \"Acid Jazz\",\n    \"Polka\", \"Retro\", \"Musical\", \"Rock & Roll\", \"Hard Rock\", \"Folk\",\n    \"Folk-Rock\", \"National Folk\", \"Swing\", \"Fast Fusion\", \"Bebob\", \"Latin\",\n    \"Revival\", \"Celtic\", \"Bluegrass\", \"Avantgarde\", \"Gothic Rock\",\n    \"Progressive Rock\", \"Psychedelic Rock\", \"Symphonic Rock\", \"Slow Rock\",\n    \"Big Band\", \"Chorus\", \"Easy Listening\", \"Acoustic\", \"Humour\", \"Speech\",\n    \"Chanson\", \"Opera\", \"Chamber Music\", \"Sonata\", \"Symphony\", \"Booty Bass\",\n    \"Primus\", \"Porn Groove\", \"Satire\", \"Slow Jam\", \"Club\", \"Tango\", \"Samba\",\n    \"Folklore\", \"Ballad\", \"Power Ballad\", \"Rhythmic Soul\", \"Freestyle\", \"Duet\",\n    \"Punk Rock\", \"Drum Solo\", \"A Cappella\", \"Euro-House\", \"Dance Hall\",\n    \"Goa\", \"Drum & Bass\", \"Club-House\", \"Hardcore\", \"Terror\", \"Indie\",\n    \"BritPop\", \"Negerpunk\", \"Polsk Punk\", \"Beat\", \"Christian Gangsta\",\n    \"Heavy Metal\", \"Black Metal\", \"Crossover\", \"Contemporary Christian\",\n    \"Christian Rock\", \"Merengue\", \"Salsa\", \"Thrash Metal\", \"Anime\", \"JPop\",\n    \"SynthPop\"\n};\n\n#define GENRE_NAME_COUNT \\\n    ((int)(sizeof genre_names / sizeof (const char *const)))\n\nstatic const int genre_alpha_map[] = {\n    123, 34, 74, 73, 99, 20, 40, 26, 145, 90, 116, 41, 135, 85, 96, 138, 89, 0,\n    107, 132, 65, 88, 104, 102, 97, 136, 61, 141, 32, 1, 112, 128, 57, 140, 2,\n    139, 58, 3, 125, 50, 22, 4, 55, 127, 122, 120, 98, 52, 48, 54, 124, 25, 84,\n    80, 115, 81, 119, 5, 30, 36, 59, 126, 38, 49, 91, 6, 129, 79, 137, 7, 35,\n    100, 131, 19, 33, 46, 47, 8, 29, 146, 63, 86, 71, 45, 142, 9, 77, 82, 64,\n    133, 10, 66, 39, 11, 103, 12, 75, 134, 13, 53, 62, 109, 117, 23, 108, 92,\n    67, 93, 43, 121, 15, 68, 14, 16, 76, 87, 118, 17, 78, 143, 114, 110, 69, 21,\n    111, 95, 105, 42, 37, 24, 56, 44, 101, 83, 94, 106, 147, 113, 18, 51, 130,\n    144, 60, 70, 31, 72, 27, 28\n};\n\n#define GENRE_ALPHA_COUNT ((int)(sizeof genre_alpha_map / sizeof (int)))\n\n#define GENRE_INDEX_OTHER 12\n\n\n#define FRAME_ID(a, b, c, d) \\\n    ( ((unsigned long)(a) << 24) \\\n    | ((unsigned long)(b) << 16) \\\n    | ((unsigned long)(c) <<  8) \\\n    | ((unsigned long)(d) <<  0) )\n\ntypedef enum UsualStringIDs { ID_TITLE = FRAME_ID('T', 'I', 'T', '2')\n        , ID_ARTIST = FRAME_ID('T', 'P', 'E', '1')\n        , ID_ALBUM = FRAME_ID('T', 'A', 'L', 'B')\n        , ID_GENRE = FRAME_ID('T', 'C', 'O', 'N')\n        , ID_ENCODER = FRAME_ID('T', 'S', 'S', 'E')\n        , ID_PLAYLENGTH = FRAME_ID('T', 'L', 'E', 'N')\n        , ID_COMMENT = FRAME_ID('C', 'O', 'M', 'M') /* full text string */\n} UsualStringIDs;\n\ntypedef enum NumericStringIDs { ID_DATE = FRAME_ID('T', 'D', 'A', 'T') /* \"ddMM\" */\n        , ID_TIME = FRAME_ID('T', 'I', 'M', 'E') /* \"hhmm\" */\n        , ID_TPOS = FRAME_ID('T', 'P', 'O', 'S') /* '0'-'9' and '/' allowed */\n        , ID_TRACK = FRAME_ID('T', 'R', 'C', 'K') /* '0'-'9' and '/' allowed */\n        , ID_YEAR = FRAME_ID('T', 'Y', 'E', 'R') /* \"yyyy\" */\n} NumericStringIDs;\n\ntypedef enum MiscIDs { ID_TXXX = FRAME_ID('T', 'X', 'X', 'X')\n        , ID_WXXX = FRAME_ID('W', 'X', 'X', 'X')\n        , ID_SYLT = FRAME_ID('S', 'Y', 'L', 'T')\n        , ID_APIC = FRAME_ID('A', 'P', 'I', 'C')\n        , ID_GEOB = FRAME_ID('G', 'E', 'O', 'B')\n        , ID_PCNT = FRAME_ID('P', 'C', 'N', 'T')\n        , ID_AENC = FRAME_ID('A', 'E', 'N', 'C')\n        , ID_LINK = FRAME_ID('L', 'I', 'N', 'K')\n        , ID_ENCR = FRAME_ID('E', 'N', 'C', 'R')\n        , ID_GRID = FRAME_ID('G', 'R', 'I', 'D')\n        , ID_PRIV = FRAME_ID('P', 'R', 'I', 'V')\n        , ID_VSLT = FRAME_ID('V', 'S', 'L', 'T') /* full text string */\n        , ID_USER = FRAME_ID('U', 'S', 'E', 'R') /* full text string */\n        , ID_PCST = FRAME_ID('P', 'C', 'S', 'T') /* iTunes Podcast indicator, only presence important */\n        , ID_WFED = FRAME_ID('W', 'F', 'E', 'D') /* iTunes Podcast URL as TEXT FRAME !!! violates standard */\n} MiscIDs;\n\n\nstatic int\nframe_id_matches(int id, int mask)\n{\n    int     result = 0, i, window = 0xff;\n    for (i = 0; i < 4; ++i, window <<= 8) {\n        int const mw = (mask & window);\n        int const iw = (id & window);\n        if (mw != 0 && mw != iw) {\n            result |= iw;\n        }\n    }\n    return result;\n}\n\nstatic int\nisFrameIdMatching(int id, int mask)\n{\n    return frame_id_matches(id, mask) == 0 ? 1 : 0;\n}\n\nstatic int\ntest_tag_spec_flags(lame_internal_flags const *gfc, unsigned int tst)\n{\n    return (gfc->tag_spec.flags & tst) != 0u ? 1 : 0;\n}\n\n#if 0\nstatic void\ndebug_tag_spec_flags(lame_internal_flags * gfc, const char* info)\n{\n    MSGF(gfc, \"%s\\n\", info);\n    MSGF(gfc, \"CHANGED_FLAG  : %d\\n\", test_tag_spec_flags(gfc, CHANGED_FLAG )); \n    MSGF(gfc, \"ADD_V2_FLAG   : %d\\n\", test_tag_spec_flags(gfc, ADD_V2_FLAG  )); \n    MSGF(gfc, \"V1_ONLY_FLAG  : %d\\n\", test_tag_spec_flags(gfc, V1_ONLY_FLAG )); \n    MSGF(gfc, \"V2_ONLY_FLAG  : %d\\n\", test_tag_spec_flags(gfc, V2_ONLY_FLAG )); \n    MSGF(gfc, \"SPACE_V1_FLAG : %d\\n\", test_tag_spec_flags(gfc, SPACE_V1_FLAG)); \n    MSGF(gfc, \"PAD_V2_FLAG   : %d\\n\", test_tag_spec_flags(gfc, PAD_V2_FLAG  )); \n}\n#endif\n\n\n\nstatic int\nid3v2_add_ucs2(lame_t gfp, uint32_t frame_id, char const *lang, unsigned short const *desc, unsigned short const *text);\nstatic int\nid3v2_add_latin1(lame_t gfp, uint32_t frame_id, char const *lang, char const *desc, char const *text);\n\nstatic void\ncopyV1ToV2(lame_t gfp, int frame_id, char const *s)\n{\n    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;\n    if (gfc != 0) {\n        unsigned int flags = gfc->tag_spec.flags;\n        id3v2_add_latin1(gfp, frame_id, \"XXX\", 0, s);\n        gfc->tag_spec.flags = flags;\n#if 0\n        debug_tag_spec_flags(gfc, \"copyV1ToV2\");\n#endif\n    }\n}\n\n\nstatic void\nid3v2AddLameVersion(lame_t gfp)\n{\n    char    buffer[1024];\n    const char *b = get_lame_os_bitness();\n    const char *v = get_lame_version();\n    const char *u = get_lame_url();\n    const size_t lenb = strlen(b);\n\n    if (lenb > 0) {\n        sprintf(buffer, \"LAME %s version %s (%s)\", b, v, u);\n    }\n    else {\n        sprintf(buffer, \"LAME version %s (%s)\", v, u);\n    }\n    copyV1ToV2(gfp, ID_ENCODER, buffer);\n}\n\nstatic void\nid3v2AddAudioDuration(lame_t gfp, double ms)\n{\n    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    char    buffer[1024];\n    double const max_ulong = MAX_U_32_NUM;\n    unsigned long playlength_ms;\n\n    ms *= 1000;\n    ms /= cfg->samplerate_in;\n    if (ms > max_ulong) {\n        playlength_ms = max_ulong;\n    }\n    else if (ms < 0) {\n        playlength_ms = 0;\n    }\n    else {\n        playlength_ms = ms;\n    }\n    sprintf(buffer, \"%lu\", playlength_ms);\n    copyV1ToV2(gfp, ID_PLAYLENGTH, buffer);\n}\n\nvoid\nid3tag_genre_list(void (*handler) (int, const char *, void *), void *cookie)\n{\n    if (handler) {\n        int     i;\n        for (i = 0; i < GENRE_NAME_COUNT; ++i) {\n            if (i < GENRE_ALPHA_COUNT) {\n                int     j = genre_alpha_map[i];\n                handler(j, genre_names[j], cookie);\n            }\n        }\n    }\n}\n\n#define GENRE_NUM_UNKNOWN 255\n\n\n\nvoid\nid3tag_init(lame_t gfp)\n{\n    lame_internal_flags *gfc = gfp->internal_flags;\n    free_id3tag(gfc);\n    memset(&gfc->tag_spec, 0, sizeof gfc->tag_spec);\n    gfc->tag_spec.genre_id3v1 = GENRE_NUM_UNKNOWN;\n    gfc->tag_spec.padding_size = 128;\n    id3v2AddLameVersion(gfp);\n}\n\n\n\nvoid\nid3tag_add_v2(lame_t gfp)\n{\n    lame_internal_flags *gfc = gfp->internal_flags;\n    gfc->tag_spec.flags &= ~V1_ONLY_FLAG;\n    gfc->tag_spec.flags |= ADD_V2_FLAG;\n}\n\nvoid\nid3tag_v1_only(lame_t gfp)\n{\n    lame_internal_flags *gfc = gfp->internal_flags;\n    gfc->tag_spec.flags &= ~(ADD_V2_FLAG | V2_ONLY_FLAG);\n    gfc->tag_spec.flags |= V1_ONLY_FLAG;\n}\n\nvoid\nid3tag_v2_only(lame_t gfp)\n{\n    lame_internal_flags *gfc = gfp->internal_flags;\n    gfc->tag_spec.flags &= ~V1_ONLY_FLAG;\n    gfc->tag_spec.flags |= V2_ONLY_FLAG;\n}\n\nvoid\nid3tag_space_v1(lame_t gfp)\n{\n    lame_internal_flags *gfc = gfp->internal_flags;\n    gfc->tag_spec.flags &= ~V2_ONLY_FLAG;\n    gfc->tag_spec.flags |= SPACE_V1_FLAG;\n}\n\nvoid\nid3tag_pad_v2(lame_t gfp)\n{\n    id3tag_set_pad(gfp, 128);\n}\n\nvoid\nid3tag_set_pad(lame_t gfp, size_t n)\n{\n    lame_internal_flags *gfc = gfp->internal_flags;\n    gfc->tag_spec.flags &= ~V1_ONLY_FLAG;\n    gfc->tag_spec.flags |= PAD_V2_FLAG;\n    gfc->tag_spec.flags |= ADD_V2_FLAG;\n    gfc->tag_spec.padding_size = (unsigned int)n;\n}\n\nstatic int\nhasUcs2ByteOrderMarker(unsigned short bom)\n{\n    if (bom == 0xFFFEu || bom == 0xFEFFu) {\n        return 1;\n    }\n    return 0;\n}\n\n\nstatic unsigned short\nswap_bytes(unsigned short w)\n{\n    return (0xff00u & (w << 8)) | (0x00ffu & (w >> 8));\n}\n\n\nstatic unsigned short\ntoLittleEndian(unsigned short bom, unsigned short c)\n{\n    if (bom == 0xFFFEu) {\n        return swap_bytes(c);\n    }\n    return c;\n}\n\nstatic unsigned short\nfromLatin1Char(const unsigned short* s, unsigned short c)\n{\n    if (s[0] == 0xFFFEu) {\n        return swap_bytes(c);\n    }\n    return c;\n}\n\n\nstatic  size_t\nlocal_strdup(char **dst, const char *src)\n{\n    if (dst == 0) {\n        return 0;\n    }\n    free(*dst);\n    *dst = 0;\n    if (src != 0) {\n        size_t  n;\n        for (n = 0; src[n] != 0; ++n) { /* calc src string length */\n        }\n        if (n > 0) {    /* string length without zero termination */\n            assert(sizeof(*src) == sizeof(**dst));\n            *dst = lame_calloc(char, n + 1);\n            if (*dst != 0) {\n                memcpy(*dst, src, n * sizeof(**dst));\n                (*dst)[n] = 0;\n                return n;\n            }\n        }\n    }\n    return 0;\n}\n\nstatic  size_t\nlocal_ucs2_strdup(unsigned short **dst, unsigned short const *src)\n{\n    if (dst == 0) {\n        return 0;\n    }\n    free(*dst);         /* free old string pointer */\n    *dst = 0;\n    if (src != 0) {\n        size_t  n;\n        for (n = 0; src[n] != 0; ++n) { /* calc src string length */\n        }\n        if (n > 0) {    /* string length without zero termination */\n            assert(sizeof(*src) >= 2);\n            assert(sizeof(*src) == sizeof(**dst));\n            *dst = lame_calloc(unsigned short, n + 1);\n            if (*dst != 0) {\n                memcpy(*dst, src, n * sizeof(**dst));\n                (*dst)[n] = 0;\n                return n;\n            }\n        }\n    }\n    return 0;\n}\n\n\nstatic  size_t\nlocal_ucs2_strlen(unsigned short const *s)\n{\n    size_t  n = 0;\n    if (s != 0) {\n        while (*s++) {\n            ++n;\n        }\n    }\n    return n;\n}\n\n\nstatic size_t\nlocal_ucs2_substr(unsigned short** dst, unsigned short const* src, size_t start, size_t end)\n{\n    size_t const len = 1 + 1 + ((start < end) ? (end - start) : 0);\n    size_t n = 0;\n    unsigned short *ptr = lame_calloc(unsigned short, len);\n    *dst = ptr;\n    if (ptr == 0 || src == 0) {\n        return 0;\n    }\n    if (hasUcs2ByteOrderMarker(src[0])) {\n        ptr[n++] = src[0];\n        if (start == 0) {\n            ++start;\n        }\n    }\n    while (start < end) {\n        ptr[n++] = src[start++];\n    }\n    ptr[n] = 0;\n    return n;\n}\n\nstatic int\nlocal_ucs2_pos(unsigned short const* str, unsigned short c)\n{\n    int     i;\n    for (i = 0; str != 0 && str[i] != 0; ++i) {\n        if (str[i] == c) {\n            return i;\n        }\n    }\n    return -1;\n}\n\nstatic int\nlocal_char_pos(char const* str, char c)\n{\n    int     i;\n    for (i = 0; str != 0 && str[i] != 0; ++i) {\n        if (str[i] == c) {\n            return i;\n        }\n    }\n    return -1;\n}\n\nstatic int\nmaybeLatin1(unsigned short const* text)\n{\n    if (text) {\n        unsigned short bom = *text++;\n        while (*text) {\n            unsigned short c = toLittleEndian(bom, *text++);\n            if (c > 0x00fe) return 0;\n        }\n    }\n    return 1;\n}\n\nstatic int searchGenre(char const* genre);\nstatic int sloppySearchGenre(char const* genre);\n\nstatic int\nlookupGenre(char const* genre)\n{\n    char   *str;\n    int     num = strtol(genre, &str, 10);\n    /* is the input a string or a valid number? */\n    if (*str) {\n        num = searchGenre(genre);\n        if (num == GENRE_NAME_COUNT) {\n            num = sloppySearchGenre(genre);\n        }\n        if (num == GENRE_NAME_COUNT) {\n            return -2; /* no common genre text found */\n        }\n    }\n    else {\n        if ((num < 0) || (num >= GENRE_NAME_COUNT)) {\n            return -1; /* number unknown */\n        }\n    }\n    return num;\n}\n\nstatic unsigned char *\nwriteLoBytes(unsigned char *frame, unsigned short const *str, size_t n);\n\nstatic char*\nlocal_strdup_utf16_to_latin1(unsigned short const* utf16)\n{\n    size_t  len = local_ucs2_strlen(utf16);\n    unsigned char* latin1 = lame_calloc(unsigned char, len+1);\n    writeLoBytes(latin1, utf16, len);\n    return (char*)latin1;\n}\n\n\nstatic int\nid3tag_set_genre_utf16(lame_t gfp, unsigned short const* text)\n{\n    lame_internal_flags* gfc = gfp->internal_flags;\n    int   ret;\n    if (text == 0) {\n        return -3;\n    }\n    if (!hasUcs2ByteOrderMarker(text[0])) {\n        return -3;\n    }\n    if (maybeLatin1(text)) {\n        char*   latin1 = local_strdup_utf16_to_latin1(text);\n        int     num = lookupGenre(latin1);\n        free(latin1);\n        if (num == -1) return -1; /* number out of range */\n        if (num >= 0) {           /* common genre found  */\n            gfc->tag_spec.flags |= CHANGED_FLAG;\n            gfc->tag_spec.genre_id3v1 = num;\n            copyV1ToV2(gfp, ID_GENRE, genre_names[num]);\n            return 0;\n        }\n    }\n    ret = id3v2_add_ucs2(gfp, ID_GENRE, 0, 0, text);\n    if (ret == 0) {\n        gfc->tag_spec.flags |= CHANGED_FLAG;\n        gfc->tag_spec.genre_id3v1 = GENRE_INDEX_OTHER;\n    }\n    return ret;\n}\n\n/*\nSome existing options for ID3 tag can be specified by --tv option\nas follows.\n--tt <value>, --tv TIT2=value\n--ta <value>, --tv TPE1=value\n--tl <value>, --tv TALB=value\n--ty <value>, --tv TYER=value\n--tn <value>, --tv TRCK=value\n--tg <value>, --tv TCON=value\n(although some are not exactly same)*/\n\nint\nid3tag_set_albumart(lame_t gfp, const char *image, size_t size)\n{\n    int     mimetype = 0;\n    unsigned char const *data = (unsigned char const *) image;\n    lame_internal_flags *gfc = gfp->internal_flags;\n\n    /* determine MIME type from the actual image data */\n    if (2 < size && data[0] == 0xFF && data[1] == 0xD8) {\n        mimetype = MIMETYPE_JPEG;\n    }\n    else if (4 < size && data[0] == 0x89 && strncmp((const char *) &data[1], \"PNG\", 3) == 0) {\n        mimetype = MIMETYPE_PNG;\n    }\n    else if (4 < size && strncmp((const char *) data, \"GIF8\", 4) == 0) {\n        mimetype = MIMETYPE_GIF;\n    }\n    else {\n        return -1;\n    }\n    if (gfc->tag_spec.albumart != 0) {\n        free(gfc->tag_spec.albumart);\n        gfc->tag_spec.albumart = 0;\n        gfc->tag_spec.albumart_size = 0;\n        gfc->tag_spec.albumart_mimetype = MIMETYPE_NONE;\n    }\n    if (size < 1) {\n        return 0;\n    }\n    gfc->tag_spec.albumart = lame_calloc(unsigned char, size);\n    if (gfc->tag_spec.albumart != 0) {\n        memcpy(gfc->tag_spec.albumart, image, size);\n        gfc->tag_spec.albumart_size = (unsigned int)size;\n        gfc->tag_spec.albumart_mimetype = mimetype;\n        gfc->tag_spec.flags |= CHANGED_FLAG;\n        id3tag_add_v2(gfp);\n    }\n    return 0;\n}\n\nstatic unsigned char *\nset_4_byte_value(unsigned char *bytes, uint32_t value)\n{\n    int     i;\n    for (i = 3; i >= 0; --i) {\n        bytes[i] = value & 0xffUL;\n        value >>= 8;\n    }\n    return bytes + 4;\n}\n\nstatic uint32_t\ntoID3v2TagId(char const *s)\n{\n    unsigned int i, x = 0;\n    if (s == 0) {\n        return 0;\n    }\n    for (i = 0; i < 4 && s[i] != 0; ++i) {\n        char const c = s[i];\n        unsigned int const u = 0x0ff & c;\n        x <<= 8;\n        x |= u;\n        if (c < 'A' || 'Z' < c) {\n            if (c < '0' || '9' < c) {\n                return 0;\n            }\n        }\n    }\n    return x;\n}\n\nstatic uint32_t\ntoID3v2TagId_ucs2(unsigned short const *s)\n{\n    unsigned int i, x = 0;\n    unsigned short bom = 0;\n    if (s == 0) {\n        return 0;\n    }\n    bom = s[0];\n    if (hasUcs2ByteOrderMarker(bom)) {\n        ++s;\n    }\n    for (i = 0; i < 4 && s[i] != 0; ++i) {\n        unsigned short const c = toLittleEndian(bom, s[i]);\n        if (c < 'A' || 'Z' < c) {\n            if (c < '0' || '9' < c) {\n                return 0;\n            }\n        }\n        x <<= 8;\n        x |= c;\n    }\n    return x;\n}\n\n#if 0\nstatic int\nisNumericString(uint32_t frame_id)\n{\n    switch (frame_id) {\n    case ID_DATE:\n    case ID_TIME:\n    case ID_TPOS:\n    case ID_TRACK:\n    case ID_YEAR:\n        return 1;\n    }\n    return 0;\n}\n#endif\n\nstatic int\nisMultiFrame(uint32_t frame_id)\n{\n    switch (frame_id) {\n    case ID_TXXX:\n    case ID_WXXX:\n    case ID_COMMENT:\n    case ID_SYLT:\n    case ID_APIC:\n    case ID_GEOB:\n    case ID_PCNT:\n    case ID_AENC:\n    case ID_LINK:\n    case ID_ENCR:\n    case ID_GRID:\n    case ID_PRIV:\n        return 1;\n    }\n    return 0;\n}\n\n#if 0\nstatic int\nisFullTextString(int frame_id)\n{\n    switch (frame_id) {\n    case ID_VSLT:\n    case ID_COMMENT:\n        return 1;\n    }\n    return 0;\n}\n#endif\n\nstatic FrameDataNode *\nfindNode(id3tag_spec const *tag, uint32_t frame_id, FrameDataNode const *last)\n{\n    FrameDataNode *node = last ? last->nxt : tag->v2_head;\n    while (node != 0) {\n        if (node->fid == frame_id) {\n            return node;\n        }\n        node = node->nxt;\n    }\n    return 0;\n}\n\nstatic void\nappendNode(id3tag_spec * tag, FrameDataNode * node)\n{\n    if (tag->v2_tail == 0 || tag->v2_head == 0) {\n        tag->v2_head = node;\n        tag->v2_tail = node;\n    }\n    else {\n        tag->v2_tail->nxt = node;\n        tag->v2_tail = node;\n    }\n}\n\nstatic void\nsetLang(char *dst, char const *src)\n{\n    int     i;\n    if (src == 0 || src[0] == 0) {\n        dst[0] = 'X';\n        dst[1] = 'X';\n        dst[2] = 'X';\n    }\n    else {\n        for (i = 0; i < 3 && src && *src; ++i) {\n            dst[i] = src[i];\n        }\n        for (; i < 3; ++i) {\n            dst[i] = ' ';\n        }\n    }\n}\n\nstatic int\nisSameLang(char const *l1, char const *l2)\n{\n    char    d[3];\n    int     i;\n    setLang(d, l2);\n    for (i = 0; i < 3; ++i) {\n        char    a = tolower(l1[i]);\n        char    b = tolower(d[i]);\n        if (a < ' ')\n            a = ' ';\n        if (b < ' ')\n            b = ' ';\n        if (a != b) {\n            return 0;\n        }\n    }\n    return 1;\n}\n\nstatic int\nisSameDescriptor(FrameDataNode const *node, char const *dsc)\n{\n    size_t  i;\n    if (node->dsc.enc == 1 && node->dsc.dim > 0) {\n        return 0;\n    }\n    for (i = 0; i < node->dsc.dim; ++i) {\n        if (!dsc || node->dsc.ptr.l[i] != dsc[i]) {\n            return 0;\n        }\n    }\n    return 1;\n}\n\nstatic int\nisSameDescriptorUcs2(FrameDataNode const *node, unsigned short const *dsc)\n{\n    size_t  i;\n    if (node->dsc.enc != 1 && node->dsc.dim > 0) {\n        return 0;\n    }\n    for (i = 0; i < node->dsc.dim; ++i) {\n        if (!dsc || node->dsc.ptr.u[i] != dsc[i]) {\n            return 0;\n        }\n    }\n    return 1;\n}\n\nstatic int\nid3v2_add_ucs2(lame_t gfp, uint32_t frame_id, char const *lang, unsigned short const *desc, unsigned short const *text)\n{\n    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;\n    if (gfc != 0) {\n        FrameDataNode *node = findNode(&gfc->tag_spec, frame_id, 0);\n        if (isMultiFrame(frame_id)) {\n            while (node) {\n                if (isSameLang(node->lng, lang)) {\n                    if (isSameDescriptorUcs2(node, desc)) {\n                        break;\n                    }\n                }\n                node = findNode(&gfc->tag_spec, frame_id, node);\n            }\n        }\n        if (node == 0) {\n            node = lame_calloc(FrameDataNode, 1);\n            if (node == 0) {\n                return -254; /* memory problem */\n            }\n            appendNode(&gfc->tag_spec, node);\n        }\n        node->fid = frame_id;\n        setLang(node->lng, lang);\n        node->dsc.dim = local_ucs2_strdup(&node->dsc.ptr.u, desc);\n        node->dsc.enc = 1;\n        node->txt.dim = local_ucs2_strdup(&node->txt.ptr.u, text);\n        node->txt.enc = 1;\n        gfc->tag_spec.flags |= (CHANGED_FLAG | ADD_V2_FLAG);\n        return 0;\n    }\n    return -255;\n}\n\nstatic int\nid3v2_add_latin1(lame_t gfp, uint32_t frame_id, char const *lang, char const *desc, char const *text)\n{\n    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;\n    if (gfc != 0) {\n        FrameDataNode *node = findNode(&gfc->tag_spec, frame_id, 0);\n        if (isMultiFrame(frame_id)) {\n            while (node) {\n                if (isSameLang(node->lng, lang)) {\n                    if (isSameDescriptor(node, desc)) {\n                        break;\n                    }\n                }\n                node = findNode(&gfc->tag_spec, frame_id, node);\n            }\n        }\n        if (node == 0) {\n            node = lame_calloc(FrameDataNode, 1);\n            if (node == 0) {\n                return -254; /* memory problem */\n            }\n            appendNode(&gfc->tag_spec, node);\n        }\n        node->fid = frame_id;\n        setLang(node->lng, lang);\n        node->dsc.dim = local_strdup(&node->dsc.ptr.l, desc);\n        node->dsc.enc = 0;\n        node->txt.dim = local_strdup(&node->txt.ptr.l, text);\n        node->txt.enc = 0;\n        gfc->tag_spec.flags |= (CHANGED_FLAG | ADD_V2_FLAG);\n        return 0;\n    }\n    return -255;\n}\n\n\nstatic int\nid3tag_set_userinfo_latin1(lame_t gfp, uint32_t id, char const *fieldvalue)\n{\n    char const separator = '=';\n    int     rc = -7;\n    int     a = local_char_pos(fieldvalue, separator);\n    if (a >= 0) {\n        char*   dup = 0;\n        local_strdup(&dup, fieldvalue);\n        dup[a] = 0;\n        rc = id3v2_add_latin1(gfp, id, \"XXX\", dup, dup+a+1);\n        free(dup);\n    }\n    return rc;\n}\n\nstatic int\nid3tag_set_userinfo_ucs2(lame_t gfp, uint32_t id, unsigned short const *fieldvalue)\n{\n    unsigned short const separator = fromLatin1Char(fieldvalue,'=');\n    int     rc = -7;\n    size_t  b = local_ucs2_strlen(fieldvalue);\n    int     a = local_ucs2_pos(fieldvalue, separator);\n    if (a >= 0) { \n        unsigned short* dsc = 0, *val = 0;\n        local_ucs2_substr(&dsc, fieldvalue, 0, a);\n        local_ucs2_substr(&val, fieldvalue, a+1, b);\n        rc = id3v2_add_ucs2(gfp, id, \"XXX\", dsc, val);\n        free(dsc);\n        free(val);\n    }\n    return rc;\n}\n\nint\nid3tag_set_textinfo_utf16(lame_t gfp, char const *id, unsigned short const *text)\n{\n    uint32_t const frame_id = toID3v2TagId(id);\n    if (frame_id == 0) {\n        return -1;\n    }\n    if (text == 0) {\n        return 0;\n    }\n    if (!hasUcs2ByteOrderMarker(text[0])) {\n        return -3;  /* BOM missing */\n    }\n    if (frame_id == ID_TXXX || frame_id == ID_WXXX || frame_id == ID_COMMENT) {\n        return id3tag_set_userinfo_ucs2(gfp, frame_id, text);\n    }\n    if (frame_id == ID_GENRE) {\n        return id3tag_set_genre_utf16(gfp, text);\n    }\n    if (frame_id == ID_PCST) {\n        return id3v2_add_ucs2(gfp, frame_id, 0, 0, text);\n    }\n    if (frame_id == ID_USER) {\n        return id3v2_add_ucs2(gfp, frame_id, \"XXX\", text, 0);\n    }\n    if (frame_id == ID_WFED) {\n        return id3v2_add_ucs2(gfp, frame_id, 0, text, 0); /* iTunes expects WFED to be a text frame */\n    }\n    if (isFrameIdMatching(frame_id, FRAME_ID('T', 0, 0, 0))\n      ||isFrameIdMatching(frame_id, FRAME_ID('W', 0, 0, 0))) {\n#if 0\n        if (isNumericString(frame_id)) {\n            return -2;  /* must be Latin-1 encoded */\n        }\n#endif\n        return id3v2_add_ucs2(gfp, frame_id, 0, 0, text);\n    }\n    return -255;        /* not supported by now */\n}\n\nextern int\nid3tag_set_textinfo_ucs2(lame_t gfp, char const *id, unsigned short const *text);\n\nint\nid3tag_set_textinfo_ucs2(lame_t gfp, char const *id, unsigned short const *text)\n{\n    return id3tag_set_textinfo_utf16(gfp, id, text);\n}\n\nint\nid3tag_set_textinfo_latin1(lame_t gfp, char const *id, char const *text)\n{\n    uint32_t const frame_id = toID3v2TagId(id);\n    if (frame_id == 0) {\n        return -1;\n    }\n    if (text == 0) {\n        return 0;\n    }\n    if (frame_id == ID_TXXX || frame_id == ID_WXXX || frame_id == ID_COMMENT) {\n        return id3tag_set_userinfo_latin1(gfp, frame_id, text);\n    }\n    if (frame_id == ID_GENRE) {\n        return id3tag_set_genre(gfp, text);\n    }\n    if (frame_id == ID_PCST) {\n        return id3v2_add_latin1(gfp, frame_id, 0, 0, text);\n    }\n    if (frame_id == ID_USER) {\n        return id3v2_add_latin1(gfp, frame_id, \"XXX\", text, 0);\n    }\n    if (frame_id == ID_WFED) {\n        return id3v2_add_latin1(gfp, frame_id, 0, text, 0); /* iTunes expects WFED to be a text frame */\n    }\n    if (isFrameIdMatching(frame_id, FRAME_ID('T', 0, 0, 0))\n      ||isFrameIdMatching(frame_id, FRAME_ID('W', 0, 0, 0))) {\n        return id3v2_add_latin1(gfp, frame_id, 0, 0, text);\n    }\n    return -255;        /* not supported by now */\n}\n\n\nint\nid3tag_set_comment_latin1(lame_t gfp, char const *lang, char const *desc, char const *text)\n{\n    return id3v2_add_latin1(gfp, ID_COMMENT, lang, desc, text);\n}\n\n\nint\nid3tag_set_comment_utf16(lame_t gfp, char const *lang, unsigned short const *desc, unsigned short const *text)\n{\n    return id3v2_add_ucs2(gfp, ID_COMMENT, lang, desc, text);\n}\n\nextern int\nid3tag_set_comment_ucs2(lame_t gfp, char const *lang, unsigned short const *desc, unsigned short const *text);\n\n\nint\nid3tag_set_comment_ucs2(lame_t gfp, char const *lang, unsigned short const *desc, unsigned short const *text)\n{\n    return id3tag_set_comment_utf16(gfp, lang, desc, text);\n}\n\n\nvoid\nid3tag_set_title(lame_t gfp, const char *title)\n{\n    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;\n    if (gfc && title && *title) {\n        local_strdup(&gfc->tag_spec.title, title);\n        gfc->tag_spec.flags |= CHANGED_FLAG;\n        copyV1ToV2(gfp, ID_TITLE, title);\n    }\n}\n\nvoid\nid3tag_set_artist(lame_t gfp, const char *artist)\n{\n    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;\n    if (gfc && artist && *artist) {\n        local_strdup(&gfc->tag_spec.artist, artist);\n        gfc->tag_spec.flags |= CHANGED_FLAG;\n        copyV1ToV2(gfp, ID_ARTIST, artist);\n    }\n}\n\nvoid\nid3tag_set_album(lame_t gfp, const char *album)\n{\n    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;\n    if (gfc && album && *album) {\n        local_strdup(&gfc->tag_spec.album, album);\n        gfc->tag_spec.flags |= CHANGED_FLAG;\n        copyV1ToV2(gfp, ID_ALBUM, album);\n    }\n}\n\nvoid\nid3tag_set_year(lame_t gfp, const char *year)\n{\n    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;\n    if (gfc && year && *year) {\n        int     num = atoi(year);\n        if (num < 0) {\n            num = 0;\n        }\n        /* limit a year to 4 digits so it fits in a version 1 tag */\n        if (num > 9999) {\n            num = 9999;\n        }\n        if (num) {\n            gfc->tag_spec.year = num;\n            gfc->tag_spec.flags |= CHANGED_FLAG;\n        }\n        copyV1ToV2(gfp, ID_YEAR, year);\n    }\n}\n\nvoid\nid3tag_set_comment(lame_t gfp, const char *comment)\n{\n    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;\n    if (gfc && comment && *comment) {\n        local_strdup(&gfc->tag_spec.comment, comment);\n        gfc->tag_spec.flags |= CHANGED_FLAG;\n        {\n            uint32_t const flags = gfc->tag_spec.flags;\n            id3v2_add_latin1(gfp, ID_COMMENT, \"XXX\", \"\", comment);\n            gfc->tag_spec.flags = flags;\n        }\n    }\n}\n\nint\nid3tag_set_track(lame_t gfp, const char *track)\n{\n    char const *trackcount;\n    lame_internal_flags *gfc = gfp != 0 ? gfp->internal_flags : 0;\n    int     ret = 0;\n\n    if (gfc && track && *track) {\n        int     num = atoi(track);\n        /* check for valid ID3v1 track number range */\n        if (num < 1 || num > 255) {\n            num = 0;\n            ret = -1;   /* track number out of ID3v1 range, ignored for ID3v1 */\n            gfc->tag_spec.flags |= (CHANGED_FLAG | ADD_V2_FLAG);\n        }\n        if (num) {\n            gfc->tag_spec.track_id3v1 = num;\n            gfc->tag_spec.flags |= CHANGED_FLAG;\n        }\n        /* Look for the total track count after a \"/\", same restrictions */\n        trackcount = strchr(track, '/');\n        if (trackcount && *trackcount) {\n            gfc->tag_spec.flags |= (CHANGED_FLAG | ADD_V2_FLAG);\n        }\n        copyV1ToV2(gfp, ID_TRACK, track);\n    }\n    return ret;\n}\n\n/* would use real \"strcasecmp\" but it isn't portable */\nstatic int\nlocal_strcasecmp(const char *s1, const char *s2)\n{\n    unsigned char c1;\n    unsigned char c2;\n    do {\n        c1 = tolower(*s1);\n        c2 = tolower(*s2);\n        if (!c1) {\n            break;\n        }\n        ++s1;\n        ++s2;\n    } while (c1 == c2);\n    return c1 - c2;\n}\n\n\nstatic \nconst char* nextUpperAlpha(const char* p, char x)\n{\n    char c;\n    for(c = toupper(*p); *p != 0; c = toupper(*++p)) {\n        if ('A' <= c && c <= 'Z') {\n            if (c != x) {\n                return p;\n            }\n        }\n    }\n    return p;\n}\n\n\nstatic int\nsloppyCompared(const char* p, const char* q)\n{\n    char cp, cq;\n    p = nextUpperAlpha(p, 0);\n    q = nextUpperAlpha(q, 0);\n    cp = toupper(*p);\n    cq = toupper(*q);\n    while (cp == cq) {\n        if (cp == 0) {\n            return 1;\n        }\n        if (p[1] == '.') { /* some abbrevation */\n            while (*q && *q++ != ' ') {\n            }\n        }\n        p = nextUpperAlpha(p, cp);\n        q = nextUpperAlpha(q, cq);\n        cp = toupper(*p);\n        cq = toupper(*q);\n    }\n    return 0;\n}\n\n\nstatic int \nsloppySearchGenre(const char *genre)\n{\n    int i;\n    for (i = 0; i < GENRE_NAME_COUNT; ++i) {\n        if (sloppyCompared(genre, genre_names[i])) {\n            return i;\n        }\n    }\n    return GENRE_NAME_COUNT;\n}\n\n\nstatic int\nsearchGenre(const char* genre)\n{\n    int i;\n    for (i = 0; i < GENRE_NAME_COUNT; ++i) {\n        if (!local_strcasecmp(genre, genre_names[i])) {\n            return i;\n        }\n    }\n    return GENRE_NAME_COUNT;\n}\n\n\nint\nid3tag_set_genre(lame_t gfp, const char *genre)\n{\n    lame_internal_flags *gfc = gfp->internal_flags;\n    int     ret = 0;\n    if (genre && *genre) {\n        int const num = lookupGenre(genre);\n        if (num == -1) return num;\n        gfc->tag_spec.flags |= CHANGED_FLAG;\n        if (num >= 0) {\n            gfc->tag_spec.genre_id3v1 = num;\n            genre = genre_names[num];\n        }\n        else {\n            gfc->tag_spec.genre_id3v1 = GENRE_INDEX_OTHER;\n            gfc->tag_spec.flags |= ADD_V2_FLAG;\n        }\n        copyV1ToV2(gfp, ID_GENRE, genre);\n    }\n    return ret;\n}\n\n\nstatic  size_t\nsizeOfNode(FrameDataNode const *node)\n{\n    size_t  n = 0;\n    if (node) {\n        n = 10;         /* header size */\n        n += 1;         /* text encoding flag */\n        switch (node->txt.enc) {\n        default:\n        case 0:\n            if (node->dsc.dim > 0) {\n                n += node->dsc.dim + 1;\n            }\n            n += node->txt.dim;\n            break;\n        case 1:\n            if (node->dsc.dim > 0) {\n                n += (node->dsc.dim+1) * 2;\n            }\n            n += node->txt.dim * 2;\n            break;\n        }\n    }\n    return n;\n}\n\nstatic  size_t\nsizeOfCommentNode(FrameDataNode const *node)\n{\n    size_t  n = 0;\n    if (node) {\n        n = 10;         /* header size */\n        n += 1;         /* text encoding flag */\n        n += 3;         /* language */\n        switch (node->dsc.enc) {\n        default:\n        case 0:\n            n += 1 + node->dsc.dim;\n            break;\n        case 1:\n            n += 2 + node->dsc.dim * 2;\n            break;\n        }\n        switch (node->txt.enc) {\n        default:\n        case 0:\n            n += node->txt.dim;\n            break;\n        case 1:\n            n += node->txt.dim * 2;\n            break;\n        }\n    }\n    return n;\n}\n\nstatic size_t\nsizeOfWxxxNode(FrameDataNode const *node)\n{\n    size_t  n = 0;\n    if (node) {\n        n = 10;         /* header size */\n        if (node->dsc.dim > 0) {\n            n += 1;         /* text encoding flag */\n            switch (node->dsc.enc) {\n            default:\n            case 0:\n                n += 1 + node->dsc.dim;\n                break;\n            case 1:\n                n += 2 + node->dsc.dim * 2;\n                break;\n            }\n        }\n        if (node->txt.dim > 0) {\n            switch (node->txt.enc) {\n            default:\n            case 0:\n                n += node->txt.dim;\n                break;\n            case 1:\n                n += node->txt.dim - 1; /* UCS2 -> Latin1, skip BOM */\n                break;\n            }\n        }\n    }\n    return n;\n}\n\nstatic unsigned char *\nwriteChars(unsigned char *frame, char const *str, size_t n)\n{\n    while (n--) {\n        *frame++ = *str++;\n    }\n    return frame;\n}\n\nstatic unsigned char *\nwriteUcs2s(unsigned char *frame, unsigned short const *str, size_t n)\n{\n    if (n > 0) {\n        unsigned short const bom = *str;\n        while (n--) {\n            unsigned short const c = toLittleEndian(bom, *str++);\n            *frame++ = 0x00ffu & c;\n            *frame++ = 0x00ffu & (c >> 8);\n        }\n    }\n    return frame;\n}\n\nstatic unsigned char *\nwriteLoBytes(unsigned char *frame, unsigned short const *str, size_t n)\n{\n    if (n > 0) {\n        unsigned short const bom = *str;\n        if (hasUcs2ByteOrderMarker(bom)) {\n            str++; n--; /* skip BOM */\n        }\n        while (n--) {\n            unsigned short const c = toLittleEndian(bom, *str++);\n            if (c < 0x0020u || 0x00ffu < c) {\n                *frame++ = 0x0020; /* blank */\n            }\n            else {\n                *frame++ = c;\n            }\n        }\n    }\n    return frame;\n}\n\nstatic unsigned char *\nset_frame_comment(unsigned char *frame, FrameDataNode const *node)\n{\n    size_t const n = sizeOfCommentNode(node);\n    if (n > 10) {\n        frame = set_4_byte_value(frame, node->fid);\n        frame = set_4_byte_value(frame, (uint32_t) (n - 10));\n        /* clear 2-byte header flags */\n        *frame++ = 0;\n        *frame++ = 0;\n        /* encoding descriptor byte */\n        *frame++ = node->txt.enc == 1 ? 1 : 0;\n        /* 3 bytes language */\n        *frame++ = node->lng[0];\n        *frame++ = node->lng[1];\n        *frame++ = node->lng[2];\n        /* descriptor with zero byte(s) separator */\n        if (node->dsc.enc != 1) {\n            frame = writeChars(frame, node->dsc.ptr.l, node->dsc.dim);\n            *frame++ = 0;\n        }\n        else {\n            frame = writeUcs2s(frame, node->dsc.ptr.u, node->dsc.dim);\n            *frame++ = 0;\n            *frame++ = 0;\n        }\n        /* comment full text */\n        if (node->txt.enc != 1) {\n            frame = writeChars(frame, node->txt.ptr.l, node->txt.dim);\n        }\n        else {\n            frame = writeUcs2s(frame, node->txt.ptr.u, node->txt.dim);\n        }\n    }\n    return frame;\n}\n\nstatic unsigned char *\nset_frame_custom2(unsigned char *frame, FrameDataNode const *node)\n{\n    size_t const n = sizeOfNode(node);\n    if (n > 10) {\n        frame = set_4_byte_value(frame, node->fid);\n        frame = set_4_byte_value(frame, (unsigned long) (n - 10));\n        /* clear 2-byte header flags */\n        *frame++ = 0;\n        *frame++ = 0;\n        /* clear 1 encoding descriptor byte to indicate ISO-8859-1 format */\n        *frame++ = node->txt.enc == 1 ? 1 : 0;\n        if (node->dsc.dim > 0) {\n            if (node->dsc.enc != 1) {\n                frame = writeChars(frame, node->dsc.ptr.l, node->dsc.dim);\n                *frame++ = 0;\n            }\n            else {\n                frame = writeUcs2s(frame, node->dsc.ptr.u, node->dsc.dim);\n                *frame++ = 0;\n                *frame++ = 0;\n            }\n        }\n        if (node->txt.enc != 1) {\n            frame = writeChars(frame, node->txt.ptr.l, node->txt.dim);\n        }\n        else {\n            frame = writeUcs2s(frame, node->txt.ptr.u, node->txt.dim);\n        }\n    }\n    return frame;\n}\n\nstatic unsigned char *\nset_frame_wxxx(unsigned char *frame, FrameDataNode const *node)\n{\n    size_t const n = sizeOfWxxxNode(node);\n    if (n > 10) {\n        frame = set_4_byte_value(frame, node->fid);\n        frame = set_4_byte_value(frame, (unsigned long) (n - 10));\n        /* clear 2-byte header flags */\n        *frame++ = 0;\n        *frame++ = 0;\n        if (node->dsc.dim > 0) {\n            /* clear 1 encoding descriptor byte to indicate ISO-8859-1 format */\n            *frame++ = node->dsc.enc == 1 ? 1 : 0;\n            if (node->dsc.enc != 1) {\n                frame = writeChars(frame, node->dsc.ptr.l, node->dsc.dim);\n                *frame++ = 0;\n            }\n            else {\n                frame = writeUcs2s(frame, node->dsc.ptr.u, node->dsc.dim);\n                *frame++ = 0;\n                *frame++ = 0;\n            }\n        }\n        if (node->txt.enc != 1) {\n            frame = writeChars(frame, node->txt.ptr.l, node->txt.dim);\n        }\n        else {\n            frame = writeLoBytes(frame, node->txt.ptr.u, node->txt.dim);\n        }\n    }\n    return frame;\n}\n\nstatic unsigned char *\nset_frame_apic(unsigned char *frame, const char *mimetype, const unsigned char *data, size_t size)\n{\n    /* ID3v2.3 standard APIC frame:\n     *     <Header for 'Attached picture', ID: \"APIC\">\n     *     Text encoding    $xx\n     *     MIME type        <text string> $00\n     *     Picture type     $xx\n     *     Description      <text string according to encoding> $00 (00)\n     *     Picture data     <binary data>\n     */\n    if (mimetype && data && size) {\n        frame = set_4_byte_value(frame, FRAME_ID('A', 'P', 'I', 'C'));\n        frame = set_4_byte_value(frame, (unsigned long) (4 + strlen(mimetype) + size));\n        /* clear 2-byte header flags */\n        *frame++ = 0;\n        *frame++ = 0;\n        /* clear 1 encoding descriptor byte to indicate ISO-8859-1 format */\n        *frame++ = 0;\n        /* copy mime_type */\n        while (*mimetype) {\n            *frame++ = *mimetype++;\n        }\n        *frame++ = 0;\n        /* set picture type to 0 */\n        *frame++ = 0;\n        /* empty description field */\n        *frame++ = 0;\n        /* copy the image data */\n        while (size--) {\n            *frame++ = *data++;\n        }\n    }\n    return frame;\n}\n\nint\nid3tag_set_fieldvalue(lame_t gfp, const char *fieldvalue)\n{\n    if (fieldvalue && *fieldvalue) {\n        if (strlen(fieldvalue) < 5 || fieldvalue[4] != '=') {\n            return -1;\n        }\n        return id3tag_set_textinfo_latin1(gfp, fieldvalue, &fieldvalue[5]);\n    }\n    return 0;\n}\n\nint\nid3tag_set_fieldvalue_utf16(lame_t gfp, const unsigned short *fieldvalue)\n{\n    if (fieldvalue && *fieldvalue) {\n        size_t dx = hasUcs2ByteOrderMarker(fieldvalue[0]);\n        unsigned short const separator = fromLatin1Char(fieldvalue, '=');\n        char fid[5] = {0,0,0,0,0};\n        uint32_t const frame_id = toID3v2TagId_ucs2(fieldvalue);\n        if (local_ucs2_strlen(fieldvalue) < (5+dx) || fieldvalue[4+dx] != separator) {\n            return -1;\n        }\n        fid[0] = (frame_id >> 24) & 0x0ff;\n        fid[1] = (frame_id >> 16) & 0x0ff;\n        fid[2] = (frame_id >> 8) & 0x0ff;\n        fid[3] = frame_id & 0x0ff;\n        if (frame_id != 0) {\n            unsigned short* txt = 0;\n            int     rc;\n            local_ucs2_substr(&txt, fieldvalue, dx+5, local_ucs2_strlen(fieldvalue));\n            rc = id3tag_set_textinfo_utf16(gfp, fid, txt);\n            free(txt);\n            return rc;\n        }\n    }\n    return -1;\n}\n\nextern int\nid3tag_set_fieldvalue_ucs2(lame_t gfp, const unsigned short *fieldvalue);\n\nint\nid3tag_set_fieldvalue_ucs2(lame_t gfp, const unsigned short *fieldvalue)\n{\n    return id3tag_set_fieldvalue_utf16(gfp, fieldvalue);\n}\n\nsize_t\nlame_get_id3v2_tag(lame_t gfp, unsigned char *buffer, size_t size)\n{\n    lame_internal_flags *gfc;\n    if (gfp == 0) {\n        return 0;\n    }\n    gfc = gfp->internal_flags;\n    if (gfc == 0) {\n        return 0;\n    }\n    if (test_tag_spec_flags(gfc, V1_ONLY_FLAG)) {\n        return 0;\n    }\n#if 0\n    debug_tag_spec_flags(gfc, \"lame_get_id3v2_tag\");\n#endif\n    {\n        int usev2 = test_tag_spec_flags(gfc, ADD_V2_FLAG | V2_ONLY_FLAG);\n        /* calculate length of four fields which may not fit in verion 1 tag */\n        size_t  title_length = gfc->tag_spec.title ? strlen(gfc->tag_spec.title) : 0;\n        size_t  artist_length = gfc->tag_spec.artist ? strlen(gfc->tag_spec.artist) : 0;\n        size_t  album_length = gfc->tag_spec.album ? strlen(gfc->tag_spec.album) : 0;\n        size_t  comment_length = gfc->tag_spec.comment ? strlen(gfc->tag_spec.comment) : 0;\n        /* write tag if explicitly requested or if fields overflow */\n        if ((title_length > 30)\n            || (artist_length > 30)\n            || (album_length > 30)\n            || (comment_length > 30)\n            || (gfc->tag_spec.track_id3v1 && (comment_length > 28))) {\n            usev2 = 1;\n        }\n        if (usev2) {\n            size_t  tag_size;\n            unsigned char *p;\n            size_t  adjusted_tag_size;\n            const char *albumart_mime = NULL;\n            static const char *mime_jpeg = \"image/jpeg\";\n            static const char *mime_png = \"image/png\";\n            static const char *mime_gif = \"image/gif\";\n\n            if (gfp->num_samples != MAX_U_32_NUM) {\n                id3v2AddAudioDuration(gfp, gfp->num_samples);\n            }\n\n            /* calulate size of tag starting with 10-byte tag header */\n            tag_size = 10;\n            if (gfc->tag_spec.albumart && gfc->tag_spec.albumart_size) {\n                switch (gfc->tag_spec.albumart_mimetype) {\n                case MIMETYPE_JPEG:\n                    albumart_mime = mime_jpeg;\n                    break;\n                case MIMETYPE_PNG:\n                    albumart_mime = mime_png;\n                    break;\n                case MIMETYPE_GIF:\n                    albumart_mime = mime_gif;\n                    break;\n                }\n                if (albumart_mime) {\n                    tag_size += 10 + 4 + strlen(albumart_mime) + gfc->tag_spec.albumart_size;\n                }\n            }\n            {\n                id3tag_spec *tag = &gfc->tag_spec;\n                if (tag->v2_head != 0) {\n                    FrameDataNode *node;\n                    for (node = tag->v2_head; node != 0; node = node->nxt) {\n                        if (node->fid == ID_COMMENT || node->fid == ID_USER) {\n                            tag_size += sizeOfCommentNode(node);\n                        }\n                        else if (isFrameIdMatching(node->fid, FRAME_ID('W',0,0,0))) {\n                            tag_size += sizeOfWxxxNode(node);\n                        }\n                        else {\n                            tag_size += sizeOfNode(node);\n                        }\n                    }\n                }\n            }\n            if (test_tag_spec_flags(gfc, PAD_V2_FLAG)) {\n                /* add some bytes of padding */\n                tag_size += gfc->tag_spec.padding_size;\n            }\n            if (size < tag_size) {\n                return tag_size;\n            }\n            if (buffer == 0) {\n                return 0;\n            }\n            p = buffer;\n            /* set tag header starting with file identifier */\n            *p++ = 'I';\n            *p++ = 'D';\n            *p++ = '3';\n            /* set version number word */\n            *p++ = 3;\n            *p++ = 0;\n            /* clear flags byte */\n            *p++ = 0;\n            /* calculate and set tag size = total size - header size */\n            adjusted_tag_size = tag_size - 10;\n            /* encode adjusted size into four bytes where most significant \n             * bit is clear in each byte, for 28-bit total */\n            *p++ = (unsigned char) ((adjusted_tag_size >> 21) & 0x7fu);\n            *p++ = (unsigned char) ((adjusted_tag_size >> 14) & 0x7fu);\n            *p++ = (unsigned char) ((adjusted_tag_size >> 7) & 0x7fu);\n            *p++ = (unsigned char) (adjusted_tag_size & 0x7fu);\n\n            /*\n             * NOTE: The remainder of the tag (frames and padding, if any)\n             * are not \"unsynchronized\" to prevent false MPEG audio headers\n             * from appearing in the bitstream.  Why?  Well, most players\n             * and utilities know how to skip the ID3 version 2 tag by now\n             * even if they don't read its contents, and it's actually\n             * very unlikely that such a false \"sync\" pattern would occur\n             * in just the simple text frames added here.\n             */\n\n            /* set each frame in tag */\n            {\n                id3tag_spec *tag = &gfc->tag_spec;\n                if (tag->v2_head != 0) {\n                    FrameDataNode *node;\n                    for (node = tag->v2_head; node != 0; node = node->nxt) {\n                        if (node->fid == ID_COMMENT || node->fid == ID_USER) {\n                            p = set_frame_comment(p, node);\n                        }\n                        else if (isFrameIdMatching(node->fid,FRAME_ID('W',0,0,0))) {\n                            p = set_frame_wxxx(p, node);\n                        }\n                        else {\n                            p = set_frame_custom2(p, node);\n                        }\n                    }\n                }\n            }\n            if (albumart_mime) {\n                p = set_frame_apic(p, albumart_mime, gfc->tag_spec.albumart,\n                                   gfc->tag_spec.albumart_size);\n            }\n            /* clear any padding bytes */\n            memset(p, 0, tag_size - (p - buffer));\n            return tag_size;\n        }\n    }\n    return 0;\n}\n\nint\nid3tag_write_v2(lame_t gfp)\n{\n    lame_internal_flags *gfc = gfp->internal_flags;\n#if 0\n    debug_tag_spec_flags(gfc, \"write v2\");\n#endif\n    if (test_tag_spec_flags(gfc, V1_ONLY_FLAG)) {\n        return 0;\n    }\n    if (test_tag_spec_flags(gfc, CHANGED_FLAG)) {\n        unsigned char *tag = 0;\n        size_t  tag_size, n;\n\n        n = lame_get_id3v2_tag(gfp, 0, 0);\n        tag = lame_calloc(unsigned char, n);\n        if (tag == 0) {\n            return -1;\n        }\n        tag_size = lame_get_id3v2_tag(gfp, tag, n);\n        if (tag_size > n) {\n            free(tag);\n            return -1;\n        }\n        else {\n            size_t  i;\n            /* write tag directly into bitstream at current position */\n            for (i = 0; i < tag_size; ++i) {\n                add_dummy_byte(gfc, tag[i], 1);\n            }\n        }\n        free(tag);\n        return (int) tag_size; /* ok, tag should not exceed 2GB */\n    }\n    return 0;\n}\n\nstatic unsigned char *\nset_text_field(unsigned char *field, const char *text, size_t size, int pad)\n{\n    while (size--) {\n        if (text && *text) {\n            *field++ = *text++;\n        }\n        else {\n            *field++ = pad;\n        }\n    }\n    return field;\n}\n\nsize_t\nlame_get_id3v1_tag(lame_t gfp, unsigned char *buffer, size_t size)\n{\n    size_t const tag_size = 128;\n    lame_internal_flags *gfc;\n\n    if (gfp == 0) {\n        return 0;\n    }\n    if (size < tag_size) {\n        return tag_size;\n    }\n    gfc = gfp->internal_flags;\n    if (gfc == 0) {\n        return 0;\n    }\n    if (buffer == 0) {\n        return 0;\n    }\n    if (test_tag_spec_flags(gfc, V2_ONLY_FLAG)) {\n        return 0;\n    }\n    if (test_tag_spec_flags(gfc, CHANGED_FLAG)) {\n        unsigned char *p = buffer;\n        int     pad = test_tag_spec_flags(gfc, SPACE_V1_FLAG) ? ' ' : 0;\n        char    year[5];\n\n        /* set tag identifier */\n        *p++ = 'T';\n        *p++ = 'A';\n        *p++ = 'G';\n        /* set each field in tag */\n        p = set_text_field(p, gfc->tag_spec.title, 30, pad);\n        p = set_text_field(p, gfc->tag_spec.artist, 30, pad);\n        p = set_text_field(p, gfc->tag_spec.album, 30, pad);\n        sprintf(year, \"%d\", gfc->tag_spec.year);\n        p = set_text_field(p, gfc->tag_spec.year ? year : NULL, 4, pad);\n        /* limit comment field to 28 bytes if a track is specified */\n        p = set_text_field(p, gfc->tag_spec.comment, gfc->tag_spec.track_id3v1 ? 28 : 30, pad);\n        if (gfc->tag_spec.track_id3v1) {\n            /* clear the next byte to indicate a version 1.1 tag */\n            *p++ = 0;\n            *p++ = gfc->tag_spec.track_id3v1;\n        }\n        *p++ = gfc->tag_spec.genre_id3v1;\n        return tag_size;\n    }\n    return 0;\n}\n\nint\nid3tag_write_v1(lame_t gfp)\n{\n    lame_internal_flags *const gfc = gfp->internal_flags;\n    size_t  i, n, m;\n    unsigned char tag[128];\n\n    m = sizeof(tag);\n    n = lame_get_id3v1_tag(gfp, tag, m);\n    if (n > m) {\n        return 0;\n    }\n    /* write tag directly into bitstream at current position */\n    for (i = 0; i < n; ++i) {\n        add_dummy_byte(gfc, tag[i], 1);\n    }\n    return (int) n;     /* ok, tag has fixed size of 128 bytes, well below 2GB */\n}\n"
  },
  {
    "path": "app/jni/libmp3lame/id3tag.h",
    "content": "\n#ifndef LAME_ID3_H\n#define LAME_ID3_H\n\n\n#define CHANGED_FLAG    (1U << 0)\n#define ADD_V2_FLAG     (1U << 1)\n#define V1_ONLY_FLAG    (1U << 2)\n#define V2_ONLY_FLAG    (1U << 3)\n#define SPACE_V1_FLAG   (1U << 4)\n#define PAD_V2_FLAG     (1U << 5)\n\nenum {\n    MIMETYPE_NONE = 0,\n    MIMETYPE_JPEG,\n    MIMETYPE_PNG,\n    MIMETYPE_GIF,\n};\n\ntypedef struct FrameDataNode {\n    struct FrameDataNode *nxt;\n    uint32_t fid;             /* Frame Identifier                 */\n    char    lng[4];          /* 3-character language descriptor  */\n    struct {\n        union {\n            char   *l;       /* ptr to Latin-1 chars             */\n            unsigned short *u; /* ptr to UCS-2 text                */\n            unsigned char *b; /* ptr to raw bytes                 */\n        } ptr;\n        size_t  dim;\n        int     enc;         /* 0:Latin-1, 1:UCS-2, 2:RAW        */\n    } dsc  , txt;\n} FrameDataNode;\n\n\ntypedef struct id3tag_spec {\n    /* private data members */\n    unsigned int flags;\n    int     year;\n    char   *title;\n    char   *artist;\n    char   *album;\n    char   *comment;\n    int     track_id3v1;\n    int     genre_id3v1;\n    unsigned char *albumart;\n    unsigned int albumart_size;\n    unsigned int padding_size;\n    int     albumart_mimetype;\n    FrameDataNode *v2_head, *v2_tail;\n} id3tag_spec;\n\n\n/* write tag into stream at current position */\nextern int id3tag_write_v2(lame_global_flags * gfp);\nextern int id3tag_write_v1(lame_global_flags * gfp);\n/*\n * NOTE: A version 2 tag will NOT be added unless one of the text fields won't\n * fit in a version 1 tag (e.g. the title string is longer than 30 characters),\n * or the \"id3tag_add_v2\" or \"id3tag_v2_only\" functions are used.\n */\n\n#endif\n"
  },
  {
    "path": "app/jni/libmp3lame/l3side.h",
    "content": "/*\n *\tLayer 3 side include file\n *\n *\tCopyright (c) 1999 Mark Taylor\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_L3SIDE_H\n#define LAME_L3SIDE_H\n\n/* max scalefactor band, max(SBMAX_l, SBMAX_s*3, (SBMAX_s-3)*3+8) */\n#define SFBMAX (SBMAX_s*3)\n\n/* Layer III side information. */\ntypedef struct {\n    int     l[1 + SBMAX_l];\n    int     s[1 + SBMAX_s];\n    int     psfb21[1 + PSFB21];\n    int     psfb12[1 + PSFB12];\n} scalefac_struct;\n\n\ntypedef struct {\n    FLOAT   l[SBMAX_l];\n    FLOAT   s[SBMAX_s][3];\n} III_psy_xmin;\n\ntypedef struct {\n    III_psy_xmin thm;\n    III_psy_xmin en;\n} III_psy_ratio;\n\ntypedef struct {\n    FLOAT   xr[576];\n    int     l3_enc[576];\n    int     scalefac[SFBMAX];\n    FLOAT   xrpow_max;\n\n    int     part2_3_length;\n    int     big_values;\n    int     count1;\n    int     global_gain;\n    int     scalefac_compress;\n    int     block_type;\n    int     mixed_block_flag;\n    int     table_select[3];\n    int     subblock_gain[3 + 1];\n    int     region0_count;\n    int     region1_count;\n    int     preflag;\n    int     scalefac_scale;\n    int     count1table_select;\n\n    int     part2_length;\n    int     sfb_lmax;\n    int     sfb_smin;\n    int     psy_lmax;\n    int     sfbmax;\n    int     psymax;\n    int     sfbdivide;\n    int     width[SFBMAX];\n    int     window[SFBMAX];\n    int     count1bits;\n    /* added for LSF */\n    const int *sfb_partition_table;\n    int     slen[4];\n\n    int     max_nonzero_coeff;\n    char    energy_above_cutoff[SFBMAX];\n} gr_info;\n\ntypedef struct {\n    gr_info tt[2][2];\n    int     main_data_begin;\n    int     private_bits;\n    int     resvDrain_pre;\n    int     resvDrain_post;\n    int     scfsi[2][4];\n} III_side_info_t;\n\n#endif\n"
  },
  {
    "path": "app/jni/libmp3lame/lame-analysis.h",
    "content": "/*\n *      GTK plotting routines source file\n *\n *      Copyright (c) 1999 Mark Taylor\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_GTKANAL_H\n#define LAME_GTKANAL_H\n\n\n#define READ_AHEAD 40   /* number of frames to read ahead */\n#define MAXMPGLAG READ_AHEAD /* if the mpg123 lag becomes bigger than this\n                                we have to stop */\n#define NUMBACK 6       /* number of frames we can back up */\n#define NUMPINFO (NUMBACK+READ_AHEAD+1)\n\n\n\nstruct plotting_data {\n    int     frameNum;        /* current frame number */\n    int     frameNum123;\n    int     num_samples;     /* number of pcm samples read for this frame */\n    double  frametime;       /* starting time of frame, in seconds */\n    double  pcmdata[2][1600];\n    double  pcmdata2[2][1152 + 1152 - DECDELAY];\n    double  xr[2][2][576];\n    double  mpg123xr[2][2][576];\n    double  ms_ratio[2];\n    double  ms_ener_ratio[2];\n\n    /* L,R, M and S values */\n    double  energy_save[4][BLKSIZE]; /* psymodel is one ahead */\n    double  energy[2][4][BLKSIZE];\n    double  pe[2][4];\n    double  thr[2][4][SBMAX_l];\n    double  en[2][4][SBMAX_l];\n    double  thr_s[2][4][3 * SBMAX_s];\n    double  en_s[2][4][3 * SBMAX_s];\n    double  ers_save[4];     /* psymodel is one ahead */\n    double  ers[2][4];\n\n    double  sfb[2][2][SBMAX_l];\n    double  sfb_s[2][2][3 * SBMAX_s];\n    double  LAMEsfb[2][2][SBMAX_l];\n    double  LAMEsfb_s[2][2][3 * SBMAX_s];\n\n    int     LAMEqss[2][2];\n    int     qss[2][2];\n    int     big_values[2][2];\n    int     sub_gain[2][2][3];\n\n    double  xfsf[2][2][SBMAX_l];\n    double  xfsf_s[2][2][3 * SBMAX_s];\n\n    int     over[2][2];\n    double  tot_noise[2][2];\n    double  max_noise[2][2];\n    double  over_noise[2][2];\n    int     over_SSD[2][2];\n    int     blocktype[2][2];\n    int     scalefac_scale[2][2];\n    int     preflag[2][2];\n    int     mpg123blocktype[2][2];\n    int     mixed[2][2];\n    int     mainbits[2][2];\n    int     sfbits[2][2];\n    int     LAMEmainbits[2][2];\n    int     LAMEsfbits[2][2];\n    int     framesize, stereo, js, ms_stereo, i_stereo, emph, bitrate, sampfreq, maindata;\n    int     crc, padding;\n    int     scfsi[2], mean_bits, resvsize;\n    int     totbits;\n};\n#ifndef plotting_data_defined\n#define plotting_data_defined\ntypedef struct plotting_data plotting_data;\n#endif\n#if 0\nextern plotting_data *pinfo;\n#endif\n#endif\n"
  },
  {
    "path": "app/jni/libmp3lame/lame.c",
    "content": "/* -*- mode: C; mode: fold -*- */\n/*\n *      LAME MP3 encoding engine\n *\n *      Copyright (c) 1999-2000 Mark Taylor\n *      Copyright (c) 2000-2005 Takehiro Tominaga\n *      Copyright (c) 2000-2011 Robert Hegemann\n *      Copyright (c) 2000-2005 Gabriel Bouvigne\n *      Copyright (c) 2000-2004 Alexander Leidinger\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: lame.c,v 1.365 2011/10/18 21:51:20 robert Exp $ */\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n\n#include <malloc.h>\n#include <string.h>\n#include \"lame.h\"\n#include \"machine.h\"\n\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"lame_global_flags.h\"\n#include \"gain_analysis.h\"\n#include \"bitstream.h\"\n#include \"quantize_pvt.h\"\n#include \"set_get.h\"\n#include \"quantize.h\"\n#include \"psymodel.h\"\n#include \"version.h\"\n#include \"VbrTag.h\"\n#include \"tables.h\"\n\n\n#if defined(__FreeBSD__) && !defined(__alpha__)\n#include <floatingpoint.h>\n#endif\n#ifdef __riscos__\n#include \"asmstuff.h\"\n#endif\n\n#ifdef __sun__\n/* woraround for SunOS 4.x, it has SEEK_* defined here */\n#include <unistd.h>\n#endif\n\n\n#define LAME_DEFAULT_QUALITY 3\n\n\nint\nis_lame_global_flags_valid(const lame_global_flags * gfp)\n{\n    if (gfp == NULL)\n        return 0;\n    if (gfp->class_id != LAME_ID)\n        return 0;\n    return 1;\n}\n\n\nint\nis_lame_internal_flags_valid(const lame_internal_flags * gfc)\n{\n    if (gfc == NULL)\n        return 0;\n    if (gfc->class_id != LAME_ID)\n        return 0;\n    return 1;\n}\n\n\n\nstatic  FLOAT\nfilter_coef(FLOAT x)\n{\n    if (x > 1.0)\n        return 0.0;\n    if (x <= 0.0)\n        return 1.0;\n\n    return cos(PI / 2 * x);\n}\n\nstatic void\nlame_init_params_ppflt(lame_internal_flags * gfc)\n{\n    SessionConfig_t *const cfg = &gfc->cfg;\n    \n    /***************************************************************/\n    /* compute info needed for polyphase filter (filter type==0, default) */\n    /***************************************************************/\n\n    int     band, maxband, minband;\n    FLOAT   freq;\n    int     lowpass_band = 32;\n    int     highpass_band = -1;\n\n    if (cfg->lowpass1 > 0) {\n        minband = 999;\n        for (band = 0; band <= 31; band++) {\n            freq = band / 31.0;\n            /* this band and above will be zeroed: */\n            if (freq >= cfg->lowpass2) {\n                lowpass_band = Min(lowpass_band, band);\n            }\n            if (cfg->lowpass1 < freq && freq < cfg->lowpass2) {\n                minband = Min(minband, band);\n            }\n        }\n\n        /* compute the *actual* transition band implemented by\n         * the polyphase filter */\n        if (minband == 999) {\n            cfg->lowpass1 = (lowpass_band - .75) / 31.0;\n        }\n        else {\n            cfg->lowpass1 = (minband - .75) / 31.0;\n        }\n        cfg->lowpass2 = lowpass_band / 31.0;\n    }\n\n    /* make sure highpass filter is within 90% of what the effective\n     * highpass frequency will be */\n    if (cfg->highpass2 > 0) {\n        if (cfg->highpass2 < .9 * (.75 / 31.0)) {\n            cfg->highpass1 = 0;\n            cfg->highpass2 = 0;\n            MSGF(gfc, \"Warning: highpass filter disabled.  \" \"highpass frequency too small\\n\");\n        }\n    }\n\n    if (cfg->highpass2 > 0) {\n        maxband = -1;\n        for (band = 0; band <= 31; band++) {\n            freq = band / 31.0;\n            /* this band and below will be zereod */\n            if (freq <= cfg->highpass1) {\n                highpass_band = Max(highpass_band, band);\n            }\n            if (cfg->highpass1 < freq && freq < cfg->highpass2) {\n                maxband = Max(maxband, band);\n            }\n        }\n        /* compute the *actual* transition band implemented by\n         * the polyphase filter */\n        cfg->highpass1 = highpass_band / 31.0;\n        if (maxband == -1) {\n            cfg->highpass2 = (highpass_band + .75) / 31.0;\n        }\n        else {\n            cfg->highpass2 = (maxband + .75) / 31.0;\n        }\n    }\n\n    for (band = 0; band < 32; band++) {\n        FLOAT fc1, fc2;\n        freq = band / 31.0f;\n        if (cfg->highpass2 > cfg->highpass1) {\n            fc1 = filter_coef((cfg->highpass2 - freq) / (cfg->highpass2 - cfg->highpass1 + 1e-20));\n        }\n        else {\n            fc1 = 1.0f;\n        }\n        if (cfg->lowpass2 > cfg->lowpass1) {\n            fc2 = filter_coef((freq - cfg->lowpass1)  / (cfg->lowpass2 - cfg->lowpass1 + 1e-20));\n        }\n        else {\n            fc2 = 1.0f;\n        }\n        gfc->sv_enc.amp_filter[band] = fc1 * fc2;\n    }\n}\n\n\nstatic void\noptimum_bandwidth(double *const lowerlimit, double *const upperlimit, const unsigned bitrate)\n{\n/*\n *  Input:\n *      bitrate     total bitrate in kbps\n *\n *   Output:\n *      lowerlimit: best lowpass frequency limit for input filter in Hz\n *      upperlimit: best highpass frequency limit for input filter in Hz\n */\n    int     table_index;\n\n    typedef struct {\n        int     bitrate;     /* only indicative value */\n        int     lowpass;\n    } band_pass_t;\n\n    const band_pass_t freq_map[] = {\n        {8, 2000},\n        {16, 3700},\n        {24, 3900},\n        {32, 5500},\n        {40, 7000},\n        {48, 7500},\n        {56, 10000},\n        {64, 11000},\n        {80, 13500},\n        {96, 15100},\n        {112, 15600},\n        {128, 17000},\n        {160, 17500},\n        {192, 18600},\n        {224, 19400},\n        {256, 19700},\n        {320, 20500}\n    };\n\n\n    table_index = nearestBitrateFullIndex(bitrate);\n\n    (void) freq_map[table_index].bitrate;\n    *lowerlimit = freq_map[table_index].lowpass;\n\n\n/*\n *  Now we try to choose a good high pass filtering frequency.\n *  This value is currently not used.\n *    For fu < 16 kHz:  sqrt(fu*fl) = 560 Hz\n *    For fu = 18 kHz:  no high pass filtering\n *  This gives:\n *\n *   2 kHz => 160 Hz\n *   3 kHz => 107 Hz\n *   4 kHz =>  80 Hz\n *   8 kHz =>  40 Hz\n *  16 kHz =>  20 Hz\n *  17 kHz =>  10 Hz\n *  18 kHz =>   0 Hz\n *\n *  These are ad hoc values and these can be optimized if a high pass is available.\n */\n/*    if (f_low <= 16000)\n        f_high = 16000. * 20. / f_low;\n    else if (f_low <= 18000)\n        f_high = 180. - 0.01 * f_low;\n    else\n        f_high = 0.;*/\n\n    /*\n     *  When we sometimes have a good highpass filter, we can add the highpass\n     *  frequency to the lowpass frequency\n     */\n\n    /*if (upperlimit != NULL)\n     *upperlimit = f_high;*/\n    (void) upperlimit;\n}\n\n\nstatic int\noptimum_samplefreq(int lowpassfreq, int input_samplefreq)\n{\n/*\n * Rules:\n *  - if possible, sfb21 should NOT be used\n *\n */\n    int     suggested_samplefreq = 44100;\n\n    if (input_samplefreq >= 48000)\n        suggested_samplefreq = 48000;\n    else if (input_samplefreq >= 44100)\n        suggested_samplefreq = 44100;\n    else if (input_samplefreq >= 32000)\n        suggested_samplefreq = 32000;\n    else if (input_samplefreq >= 24000)\n        suggested_samplefreq = 24000;\n    else if (input_samplefreq >= 22050)\n        suggested_samplefreq = 22050;\n    else if (input_samplefreq >= 16000)\n        suggested_samplefreq = 16000;\n    else if (input_samplefreq >= 12000)\n        suggested_samplefreq = 12000;\n    else if (input_samplefreq >= 11025)\n        suggested_samplefreq = 11025;\n    else if (input_samplefreq >= 8000)\n        suggested_samplefreq = 8000;\n\n    if (lowpassfreq == -1)\n        return suggested_samplefreq;\n\n    if (lowpassfreq <= 15960)\n        suggested_samplefreq = 44100;\n    if (lowpassfreq <= 15250)\n        suggested_samplefreq = 32000;\n    if (lowpassfreq <= 11220)\n        suggested_samplefreq = 24000;\n    if (lowpassfreq <= 9970)\n        suggested_samplefreq = 22050;\n    if (lowpassfreq <= 7230)\n        suggested_samplefreq = 16000;\n    if (lowpassfreq <= 5420)\n        suggested_samplefreq = 12000;\n    if (lowpassfreq <= 4510)\n        suggested_samplefreq = 11025;\n    if (lowpassfreq <= 3970)\n        suggested_samplefreq = 8000;\n\n    if (input_samplefreq < suggested_samplefreq) {\n        /* choose a valid MPEG sample frequency above the input sample frequency\n           to avoid SFB21/12 bitrate bloat\n           rh 061115\n         */\n        if (input_samplefreq > 44100) {\n            return 48000;\n        }\n        if (input_samplefreq > 32000) {\n            return 44100;\n        }\n        if (input_samplefreq > 24000) {\n            return 32000;\n        }\n        if (input_samplefreq > 22050) {\n            return 24000;\n        }\n        if (input_samplefreq > 16000) {\n            return 22050;\n        }\n        if (input_samplefreq > 12000) {\n            return 16000;\n        }\n        if (input_samplefreq > 11025) {\n            return 12000;\n        }\n        if (input_samplefreq > 8000) {\n            return 11025;\n        }\n        return 8000;\n    }\n    return suggested_samplefreq;\n}\n\n\n\n\n\n/* set internal feature flags.  USER should not access these since\n * some combinations will produce strange results */\nstatic void\nlame_init_qval(lame_global_flags * gfp)\n{\n    lame_internal_flags *const gfc = gfp->internal_flags;\n    SessionConfig_t *const cfg = &gfc->cfg;\n\n    switch (gfp->quality) {\n    default:\n    case 9:            /* no psymodel, no noise shaping */\n        cfg->noise_shaping = 0;\n        cfg->noise_shaping_amp = 0;\n        cfg->noise_shaping_stop = 0;\n        cfg->use_best_huffman = 0;\n        cfg->full_outer_loop = 0;\n        break;\n\n    case 8:\n        gfp->quality = 7;\n        /*lint --fallthrough */\n    case 7:            /* use psymodel (for short block and m/s switching), but no noise shapping */\n        cfg->noise_shaping = 0;\n        cfg->noise_shaping_amp = 0;\n        cfg->noise_shaping_stop = 0;\n        cfg->use_best_huffman = 0;\n        cfg->full_outer_loop = 0;\n        if (gfp->VBR == vbr_mt || gfp->VBR == vbr_mtrh) {\n            cfg->full_outer_loop  = -1;\n        }\n        break;\n\n    case 6:\n        if (cfg->noise_shaping == 0)\n            cfg->noise_shaping = 1;\n        cfg->noise_shaping_amp = 0;\n        cfg->noise_shaping_stop = 0;\n        if (cfg->subblock_gain == -1)\n            cfg->subblock_gain = 1;\n        cfg->use_best_huffman = 0;\n        cfg->full_outer_loop = 0;\n        break;\n\n    case 5:\n        if (cfg->noise_shaping == 0)\n            cfg->noise_shaping = 1;\n        cfg->noise_shaping_amp = 0;\n        cfg->noise_shaping_stop = 0;\n        if (cfg->subblock_gain == -1)\n            cfg->subblock_gain = 1;\n        cfg->use_best_huffman = 0;\n        cfg->full_outer_loop = 0;\n        break;\n\n    case 4:\n        if (cfg->noise_shaping == 0)\n            cfg->noise_shaping = 1;\n        cfg->noise_shaping_amp = 0;\n        cfg->noise_shaping_stop = 0;\n        if (cfg->subblock_gain == -1)\n            cfg->subblock_gain = 1;\n        cfg->use_best_huffman = 1;\n        cfg->full_outer_loop = 0;\n        break;\n\n    case 3:\n        if (cfg->noise_shaping == 0)\n            cfg->noise_shaping = 1;\n        cfg->noise_shaping_amp = 1;\n        cfg->noise_shaping_stop = 1;\n        if (cfg->subblock_gain == -1)\n            cfg->subblock_gain = 1;\n        cfg->use_best_huffman = 1;\n        cfg->full_outer_loop = 0;\n        break;\n\n    case 2:\n        if (cfg->noise_shaping == 0)\n            cfg->noise_shaping = 1;\n        if (gfc->sv_qnt.substep_shaping == 0)\n            gfc->sv_qnt.substep_shaping = 2;\n        cfg->noise_shaping_amp = 1;\n        cfg->noise_shaping_stop = 1;\n        if (cfg->subblock_gain == -1)\n            cfg->subblock_gain = 1;\n        cfg->use_best_huffman = 1; /* inner loop */\n        cfg->full_outer_loop = 0;\n        break;\n\n    case 1:\n        if (cfg->noise_shaping == 0)\n            cfg->noise_shaping = 1;\n        if (gfc->sv_qnt.substep_shaping == 0)\n            gfc->sv_qnt.substep_shaping = 2;\n        cfg->noise_shaping_amp = 2;\n        cfg->noise_shaping_stop = 1;\n        if (cfg->subblock_gain == -1)\n            cfg->subblock_gain = 1;\n        cfg->use_best_huffman = 1;\n        cfg->full_outer_loop = 0;\n        break;\n\n    case 0:\n        if (cfg->noise_shaping == 0)\n            cfg->noise_shaping = 1;\n        if (gfc->sv_qnt.substep_shaping == 0)\n            gfc->sv_qnt.substep_shaping = 2;\n        cfg->noise_shaping_amp = 2;\n        cfg->noise_shaping_stop = 1;\n        if (cfg->subblock_gain == -1)\n            cfg->subblock_gain = 1;\n        cfg->use_best_huffman = 1; /*type 2 disabled because of it slowness,\n                                      in favor of full outer loop search */\n        cfg->full_outer_loop = 1;\n        break;\n    }\n\n}\n\n\n\nstatic double\nlinear_int(double a, double b, double m)\n{\n    return a + m * (b - a);\n}\n\n\n\n/********************************************************************\n *   initialize internal params based on data in gf\n *   (globalflags struct filled in by calling program)\n *\n *  OUTLINE:\n *\n * We first have some complex code to determine bitrate,\n * output samplerate and mode.  It is complicated by the fact\n * that we allow the user to set some or all of these parameters,\n * and need to determine best possible values for the rest of them:\n *\n *  1. set some CPU related flags\n *  2. check if we are mono->mono, stereo->mono or stereo->stereo\n *  3.  compute bitrate and output samplerate:\n *          user may have set compression ratio\n *          user may have set a bitrate\n *          user may have set a output samplerate\n *  4. set some options which depend on output samplerate\n *  5. compute the actual compression ratio\n *  6. set mode based on compression ratio\n *\n *  The remaining code is much simpler - it just sets options\n *  based on the mode & compression ratio:\n *\n *   set allow_diff_short based on mode\n *   select lowpass filter based on compression ratio & mode\n *   set the bitrate index, and min/max bitrates for VBR modes\n *   disable VBR tag if it is not appropriate\n *   initialize the bitstream\n *   initialize scalefac_band data\n *   set sideinfo_len (based on channels, CRC, out_samplerate)\n *   write an id3v2 tag into the bitstream\n *   write VBR tag into the bitstream\n *   set mpeg1/2 flag\n *   estimate the number of frames (based on a lot of data)\n *\n *   now we set more flags:\n *   nspsytune:\n *      see code\n *   VBR modes\n *      see code\n *   CBR/ABR\n *      see code\n *\n *  Finally, we set the algorithm flags based on the gfp->quality value\n *  lame_init_qval(gfp);\n *\n ********************************************************************/\nint\nlame_init_params(lame_global_flags * gfp)\n{\n\n    int     i;\n    int     j;\n    lame_internal_flags *const gfc = gfp->internal_flags;\n    SessionConfig_t *const cfg = &gfc->cfg;\n\n    gfc->class_id = 0;\n\n    cfg->enforce_min_bitrate = gfp->VBR_hard_min;\n    cfg->analysis = gfp->analysis;\n    if (cfg->analysis)\n        gfp->write_lame_tag = 0;\n\n    /* some file options not allowed if output is: not specified or stdout */\n    if (gfc->pinfo != NULL)\n        gfp->write_lame_tag = 0; /* disable Xing VBR tag */\n\n    /* report functions */\n    gfc->report_msg = gfp->report.msgf;\n    gfc->report_dbg = gfp->report.debugf;\n    gfc->report_err = gfp->report.errorf;\n\n    if (gfp->asm_optimizations.amd3dnow)\n        gfc->CPU_features.AMD_3DNow = has_3DNow();\n    else\n        gfc->CPU_features.AMD_3DNow = 0;\n\n    if (gfp->asm_optimizations.mmx)\n        gfc->CPU_features.MMX = has_MMX();\n    else\n        gfc->CPU_features.MMX = 0;\n\n    if (gfp->asm_optimizations.sse) {\n        gfc->CPU_features.SSE = has_SSE();\n        gfc->CPU_features.SSE2 = has_SSE2();\n    }\n    else {\n        gfc->CPU_features.SSE = 0;\n        gfc->CPU_features.SSE2 = 0;\n    }\n\n\n    if (NULL == gfc->ATH)\n        gfc->ATH = calloc(1, sizeof(ATH_t));\n\n    if (NULL == gfc->ATH)\n        return -2;      /* maybe error codes should be enumerated in lame.h ?? */\n\n    if (NULL == gfc->sv_rpg.rgdata)\n        gfc->sv_rpg.rgdata = calloc(1, sizeof(replaygain_t));\n    if (NULL == gfc->sv_rpg.rgdata) {\n        freegfc(gfc);\n        gfp->internal_flags = NULL;\n        return -2;\n    }\n\n    cfg->error_protection = gfp->error_protection;\n    cfg->copyright = gfp->copyright;\n    cfg->original = gfp->original;\n    cfg->extension = gfp->extension;\n    cfg->emphasis = gfp->emphasis;\n\n    cfg->channels_in = gfp->num_channels;\n    if (cfg->channels_in == 1)\n        gfp->mode = MONO;\n    cfg->channels_out = (gfp->mode == MONO) ? 1 : 2;\n    if (gfp->mode == MONO)\n        gfp->force_ms = 0; /* don't allow forced mid/side stereo for mono output */\n    cfg->force_ms = gfp->force_ms;\n\n    if (gfp->VBR == vbr_off && gfp->VBR_mean_bitrate_kbps != 128 && gfp->brate == 0)\n        gfp->brate = gfp->VBR_mean_bitrate_kbps;\n\n    switch (gfp->VBR) {\n    case vbr_off:\n    case vbr_mtrh:\n    case vbr_mt:\n        /* these modes can handle free format condition */\n        break;\n    default:\n        gfp->free_format = 0; /* mode can't be mixed with free format */\n        break;\n    }\n\n    cfg->free_format = gfp->free_format;\n\n    if (gfp->VBR == vbr_off && gfp->brate == 0) {\n        /* no bitrate or compression ratio specified, use 11.025 */\n        if (EQ(gfp->compression_ratio, 0))\n            gfp->compression_ratio = 11.025; /* rate to compress a CD down to exactly 128000 bps */\n    }\n\n    /* find bitrate if user specify a compression ratio */\n    if (gfp->VBR == vbr_off && gfp->compression_ratio > 0) {\n\n        if (gfp->samplerate_out == 0)\n            gfp->samplerate_out = map2MP3Frequency((int) (0.97 * gfp->samplerate_in)); /* round up with a margin of 3% */\n\n        /* choose a bitrate for the output samplerate which achieves\n         * specified compression ratio\n         */\n        gfp->brate = gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->compression_ratio);\n\n        /* we need the version for the bitrate table look up */\n        cfg->samplerate_index = SmpFrqIndex(gfp->samplerate_out, &cfg->version);\n\n        if (!cfg->free_format) /* for non Free Format find the nearest allowed bitrate */\n            gfp->brate = FindNearestBitrate(gfp->brate, cfg->version, gfp->samplerate_out);\n    }\n    if (gfp->samplerate_out) {\n        if (gfp->samplerate_out < 16000) {\n            gfp->VBR_mean_bitrate_kbps = Max(gfp->VBR_mean_bitrate_kbps, 8);\n            gfp->VBR_mean_bitrate_kbps = Min(gfp->VBR_mean_bitrate_kbps, 64);\n        }\n        else if (gfp->samplerate_out < 32000) {\n            gfp->VBR_mean_bitrate_kbps = Max(gfp->VBR_mean_bitrate_kbps, 8);\n            gfp->VBR_mean_bitrate_kbps = Min(gfp->VBR_mean_bitrate_kbps, 160);\n        }\n        else {\n            gfp->VBR_mean_bitrate_kbps = Max(gfp->VBR_mean_bitrate_kbps, 32);\n            gfp->VBR_mean_bitrate_kbps = Min(gfp->VBR_mean_bitrate_kbps, 320);\n        }\n    }\n    /* WORK IN PROGRESS */\n    /* mapping VBR scale to internal VBR quality settings */\n    if (gfp->samplerate_out == 0 && (gfp->VBR == vbr_mt || gfp->VBR == vbr_mtrh)) {\n        float const qval = gfp->VBR_q + gfp->VBR_q_frac;\n        struct q_map { int sr_a; float qa, qb, ta, tb; int lp; };\n        struct q_map const m[9]\n        = { {48000, 0.0,6.5,  0.0,6.5, 23700}\n          , {44100, 0.0,6.5,  0.0,6.5, 21780}\n          , {32000, 6.5,8.0,  5.2,6.5, 15800}\n          , {24000, 8.0,8.5,  5.2,6.0, 11850}\n          , {22050, 8.5,9.01, 5.2,6.5, 10892}\n          , {16000, 9.01,9.4, 4.9,6.5,  7903}\n          , {12000, 9.4,9.6,  4.5,6.0,  5928}\n          , {11025, 9.6,9.9,  5.1,6.5,  5446}\n          , { 8000, 9.9,10.,  4.9,6.5,  3952}\n        };\n        for (i = 2; i < 9; ++i) {\n            if (gfp->samplerate_in == m[i].sr_a) {\n                if (qval < m[i].qa) {\n                    double d = qval / m[i].qa;\n                    d = d * m[i].ta;\n                    gfp->VBR_q = (int)d;\n                    gfp->VBR_q_frac = d - gfp->VBR_q;\n                }\n            }\n            if (gfp->samplerate_in >= m[i].sr_a) {\n                if (m[i].qa <= qval && qval < m[i].qb) {\n                    float const q_ = m[i].qb-m[i].qa;\n                    float const t_ = m[i].tb-m[i].ta;\n                    double d = m[i].ta + t_ * (qval-m[i].qa) / q_;\n                    gfp->VBR_q = (int)d;\n                    gfp->VBR_q_frac = d - gfp->VBR_q;\n                    gfp->samplerate_out = m[i].sr_a;\n                    if (gfp->lowpassfreq == 0) {\n                        gfp->lowpassfreq = -1;\n                    }\n                    break;\n                }\n            }\n        }\n    }\n\n    /****************************************************************/\n    /* if a filter has not been enabled, see if we should add one: */\n    /****************************************************************/\n    if (gfp->lowpassfreq == 0) {\n        double  lowpass = 16000;\n        double  highpass;\n\n        switch (gfp->VBR) {\n        case vbr_off:{\n                optimum_bandwidth(&lowpass, &highpass, gfp->brate);\n                break;\n            }\n        case vbr_abr:{\n                optimum_bandwidth(&lowpass, &highpass, gfp->VBR_mean_bitrate_kbps);\n                break;\n            }\n        case vbr_rh:{\n                int const x[11] = {\n                    19500, 19000, 18600, 18000, 17500, 16000, 15600, 14900, 12500, 10000, 3950\n                };\n                if (0 <= gfp->VBR_q && gfp->VBR_q <= 9) {\n                    double  a = x[gfp->VBR_q], b = x[gfp->VBR_q + 1], m = gfp->VBR_q_frac;\n                    lowpass = linear_int(a, b, m);\n                }\n                else {\n                    lowpass = 19500;\n                }\n                break;\n            }\n        case vbr_mtrh:\n        case vbr_mt:{\n                int const x[11] = {\n                    24000, 19500, 18500, 18000, 17500, 17000, 16500, 15600, 15200, 7230, 3950\n                };\n                if (0 <= gfp->VBR_q && gfp->VBR_q <= 9) {\n                    double  a = x[gfp->VBR_q], b = x[gfp->VBR_q + 1], m = gfp->VBR_q_frac;\n                    lowpass = linear_int(a, b, m);\n                }\n                else {\n                    lowpass = 21500;\n                }\n                break;\n            }\n        default:{\n                int const x[11] = {\n                    19500, 19000, 18500, 18000, 17500, 16500, 15500, 14500, 12500, 9500, 3950\n                };\n                if (0 <= gfp->VBR_q && gfp->VBR_q <= 9) {\n                    double  a = x[gfp->VBR_q], b = x[gfp->VBR_q + 1], m = gfp->VBR_q_frac;\n                    lowpass = linear_int(a, b, m);\n                }\n                else {\n                    lowpass = 19500;\n                }\n            }\n        }\n\n        if (gfp->mode == MONO && (gfp->VBR == vbr_off || gfp->VBR == vbr_abr))\n            lowpass *= 1.5;\n\n        gfp->lowpassfreq = lowpass;\n    }\n\n    if (gfp->samplerate_out == 0) {\n        if (2 * gfp->lowpassfreq > gfp->samplerate_in) {\n            gfp->lowpassfreq = gfp->samplerate_in / 2;\n        }\n        gfp->samplerate_out = optimum_samplefreq((int) gfp->lowpassfreq, gfp->samplerate_in);\n    }\n    if (gfp->VBR == vbr_mt || gfp->VBR == vbr_mtrh) {\n        gfp->lowpassfreq = Min(24000, gfp->lowpassfreq);\n    }\n    else {\n        gfp->lowpassfreq = Min(20500, gfp->lowpassfreq);\n    }\n    gfp->lowpassfreq = Min(gfp->samplerate_out / 2, gfp->lowpassfreq);\n\n    if (gfp->VBR == vbr_off) {\n        gfp->compression_ratio = gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->brate);\n    }\n    if (gfp->VBR == vbr_abr) {\n        gfp->compression_ratio =\n            gfp->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->VBR_mean_bitrate_kbps);\n    }\n\n    /* do not compute ReplayGain values and do not find the peak sample\n       if we can't store them */\n    if (!gfp->write_lame_tag) {\n        gfp->findReplayGain = 0;\n        gfp->decode_on_the_fly = 0;\n        cfg->findPeakSample = 0;\n    }\n\n    cfg->findReplayGain = gfp->findReplayGain;\n    cfg->decode_on_the_fly = gfp->decode_on_the_fly;\n\n    if (cfg->decode_on_the_fly)\n        cfg->findPeakSample = 1;\n\n    if (cfg->findReplayGain) {\n        if (InitGainAnalysis(gfc->sv_rpg.rgdata, gfp->samplerate_out) == INIT_GAIN_ANALYSIS_ERROR) {\n            freegfc(gfc);\n            gfp->internal_flags = NULL;\n            return -6;\n        }\n    }\n\n#ifdef DECODE_ON_THE_FLY\n    if (cfg->decode_on_the_fly && !gfp->decode_only) {\n        if (gfc->hip) {\n            hip_decode_exit(gfc->hip);\n        }\n        gfc->hip = hip_decode_init();\n        /* report functions */\n        hip_set_errorf(gfc->hip, gfp->report.errorf);\n        hip_set_debugf(gfc->hip, gfp->report.debugf);\n        hip_set_msgf(gfc->hip, gfp->report.msgf);\n    }\n#endif\n\n    cfg->disable_reservoir = gfp->disable_reservoir;\n    cfg->lowpassfreq = gfp->lowpassfreq;\n    cfg->highpassfreq = gfp->highpassfreq;\n    cfg->samplerate_in = gfp->samplerate_in;\n    cfg->samplerate_out = gfp->samplerate_out;\n    cfg->mode_gr = cfg->samplerate_out <= 24000 ? 1 : 2; /* Number of granules per frame */\n    gfc->ov_enc.encoder_delay = ENCDELAY;\n\n\n    /*\n     *  sample freq       bitrate     compression ratio\n     *     [kHz]      [kbps/channel]   for 16 bit input\n     *     44.1            56               12.6\n     *     44.1            64               11.025\n     *     44.1            80                8.82\n     *     22.05           24               14.7\n     *     22.05           32               11.025\n     *     22.05           40                8.82\n     *     16              16               16.0\n     *     16              24               10.667\n     *\n     */\n    /*\n     *  For VBR, take a guess at the compression_ratio.\n     *  For example:\n     *\n     *    VBR_q    compression     like\n     *     -        4.4         320 kbps/44 kHz\n     *   0...1      5.5         256 kbps/44 kHz\n     *     2        7.3         192 kbps/44 kHz\n     *     4        8.8         160 kbps/44 kHz\n     *     6       11           128 kbps/44 kHz\n     *     9       14.7          96 kbps\n     *\n     *  for lower bitrates, downsample with --resample\n     */\n\n    switch (gfp->VBR) {\n    case vbr_mt:\n    case vbr_rh:\n    case vbr_mtrh:\n        {\n            /*numbers are a bit strange, but they determine the lowpass value */\n            FLOAT const cmp[] = { 5.7, 6.5, 7.3, 8.2, 10, 11.9, 13, 14, 15, 16.5 };\n            gfp->compression_ratio = cmp[gfp->VBR_q];\n        }\n        break;\n    case vbr_abr:\n        gfp->compression_ratio =\n            cfg->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->VBR_mean_bitrate_kbps);\n        break;\n    default:\n        gfp->compression_ratio = cfg->samplerate_out * 16 * cfg->channels_out / (1.e3 * gfp->brate);\n        break;\n    }\n\n\n    /* mode = -1 (not set by user) or\n     * mode = MONO (because of only 1 input channel).\n     * If mode has not been set, then select J-STEREO\n     */\n    if (gfp->mode == NOT_SET) {\n        gfp->mode = JOINT_STEREO;\n    }\n\n    cfg->mode = gfp->mode;\n\n\n    /* apply user driven high pass filter */\n    if (cfg->highpassfreq > 0) {\n        cfg->highpass1 = 2. * cfg->highpassfreq;\n\n        if (gfp->highpasswidth >= 0)\n            cfg->highpass2 = 2. * (cfg->highpassfreq + gfp->highpasswidth);\n        else            /* 0% above on default */\n            cfg->highpass2 = (1 + 0.00) * 2. * cfg->highpassfreq;\n\n        cfg->highpass1 /= cfg->samplerate_out;\n        cfg->highpass2 /= cfg->samplerate_out;\n    }\n    else {\n        cfg->highpass1 = 0;\n        cfg->highpass2 = 0;\n    }\n    /* apply user driven low pass filter */\n    cfg->lowpass1 = 0;\n    cfg->lowpass2 = 0;\n    if (cfg->lowpassfreq > 0 && cfg->lowpassfreq < (cfg->samplerate_out / 2) ) {\n        cfg->lowpass2 = 2. * cfg->lowpassfreq;\n        if (gfp->lowpasswidth >= 0) {\n            cfg->lowpass1 = 2. * (cfg->lowpassfreq - gfp->lowpasswidth);\n            if (cfg->lowpass1 < 0) /* has to be >= 0 */\n                cfg->lowpass1 = 0;\n        }\n        else {          /* 0% below on default */\n            cfg->lowpass1 = (1 - 0.00) * 2. * cfg->lowpassfreq;\n        }\n        cfg->lowpass1 /= cfg->samplerate_out;\n        cfg->lowpass2 /= cfg->samplerate_out;\n    }\n\n\n\n\n  /**********************************************************************/\n    /* compute info needed for polyphase filter (filter type==0, default) */\n  /**********************************************************************/\n    lame_init_params_ppflt(gfc);\n\n\n  /*******************************************************\n   * samplerate and bitrate index\n   *******************************************************/\n    cfg->samplerate_index = SmpFrqIndex(cfg->samplerate_out, &cfg->version);\n    if (cfg->samplerate_index < 0) {\n        freegfc(gfc);\n        gfp->internal_flags = NULL;\n        return -1;\n    }\n\n    if (gfp->VBR == vbr_off) {\n        if (cfg->free_format) {\n            gfc->ov_enc.bitrate_index = 0;\n        }\n        else {\n            gfp->brate = FindNearestBitrate(gfp->brate, cfg->version, cfg->samplerate_out);\n            gfc->ov_enc.bitrate_index = BitrateIndex(gfp->brate, cfg->version, cfg->samplerate_out);\n            if (gfc->ov_enc.bitrate_index <= 0) {\n                freegfc(gfc);\n                gfp->internal_flags = NULL;\n                return -1;\n            }\n        }\n    }\n    else {\n        gfc->ov_enc.bitrate_index = 1;\n    }\n\n    init_bit_stream_w(gfc);\n\n    j = cfg->samplerate_index + (3 * cfg->version) + 6 * (cfg->samplerate_out < 16000);\n    for (i = 0; i < SBMAX_l + 1; i++)\n        gfc->scalefac_band.l[i] = sfBandIndex[j].l[i];\n\n    for (i = 0; i < PSFB21 + 1; i++) {\n        int const size = (gfc->scalefac_band.l[22] - gfc->scalefac_band.l[21]) / PSFB21;\n        int const start = gfc->scalefac_band.l[21] + i * size;\n        gfc->scalefac_band.psfb21[i] = start;\n    }\n    gfc->scalefac_band.psfb21[PSFB21] = 576;\n\n    for (i = 0; i < SBMAX_s + 1; i++)\n        gfc->scalefac_band.s[i] = sfBandIndex[j].s[i];\n\n    for (i = 0; i < PSFB12 + 1; i++) {\n        int const size = (gfc->scalefac_band.s[13] - gfc->scalefac_band.s[12]) / PSFB12;\n        int const start = gfc->scalefac_band.s[12] + i * size;\n        gfc->scalefac_band.psfb12[i] = start;\n    }\n    gfc->scalefac_band.psfb12[PSFB12] = 192;\n\n    /* determine the mean bitrate for main data */\n    if (cfg->mode_gr == 2) /* MPEG 1 */\n        cfg->sideinfo_len = (cfg->channels_out == 1) ? 4 + 17 : 4 + 32;\n    else                /* MPEG 2 */\n        cfg->sideinfo_len = (cfg->channels_out == 1) ? 4 + 9 : 4 + 17;\n\n    if (cfg->error_protection)\n        cfg->sideinfo_len += 2;\n\n    gfc->class_id = LAME_ID;\n\n    {\n        int     k;\n\n        for (k = 0; k < 19; k++)\n            gfc->sv_enc.pefirbuf[k] = 700 * cfg->mode_gr * cfg->channels_out;\n\n        if (gfp->ATHtype == -1)\n            gfp->ATHtype = 4;\n    }\n\n    assert(gfp->VBR_q <= 9);\n    assert(gfp->VBR_q >= 0);\n\n    switch (gfp->VBR) {\n\n    case vbr_mt:\n    case vbr_mtrh:{\n            if (gfp->strict_ISO < 0) {\n                gfp->strict_ISO = MDB_MAXIMUM;\n            }\n            if (gfp->useTemporal < 0) {\n                gfp->useTemporal = 0; /* off by default for this VBR mode */\n            }\n\n            (void) apply_preset(gfp, 500 - (gfp->VBR_q * 10), 0);\n            /*  The newer VBR code supports only a limited\n               subset of quality levels:\n               9-5=5 are the same, uses x^3/4 quantization\n               4-0=0 are the same  5 plus best huffman divide code\n             */\n            if (gfp->quality < 0)\n                gfp->quality = LAME_DEFAULT_QUALITY;\n            if (gfp->quality < 5)\n                gfp->quality = 0;\n            if (gfp->quality > 7)\n                gfp->quality = 7;\n\n            /*  sfb21 extra only with MPEG-1 at higher sampling rates\n             */\n            if (gfp->experimentalY)\n                gfc->sv_qnt.sfb21_extra = 0;\n            else\n                gfc->sv_qnt.sfb21_extra = (cfg->samplerate_out > 44000);\n\n            gfc->iteration_loop = VBR_new_iteration_loop;\n            break;\n\n        }\n    case vbr_rh:{\n\n            (void) apply_preset(gfp, 500 - (gfp->VBR_q * 10), 0);\n\n            /*  sfb21 extra only with MPEG-1 at higher sampling rates\n             */\n            if (gfp->experimentalY)\n                gfc->sv_qnt.sfb21_extra = 0;\n            else\n                gfc->sv_qnt.sfb21_extra = (cfg->samplerate_out > 44000);\n\n            /*  VBR needs at least the output of GPSYCHO,\n             *  so we have to garantee that by setting a minimum\n             *  quality level, actually level 6 does it.\n             *  down to level 6\n             */\n            if (gfp->quality > 6)\n                gfp->quality = 6;\n\n\n            if (gfp->quality < 0)\n                gfp->quality = LAME_DEFAULT_QUALITY;\n\n            gfc->iteration_loop = VBR_old_iteration_loop;\n            break;\n        }\n\n    default:           /* cbr/abr */  {\n            vbr_mode vbrmode;\n\n            /*  no sfb21 extra with CBR code\n             */\n            gfc->sv_qnt.sfb21_extra = 0;\n\n            if (gfp->quality < 0)\n                gfp->quality = LAME_DEFAULT_QUALITY;\n\n\n            vbrmode = gfp->VBR;\n            if (vbrmode == vbr_off)\n                (void) lame_set_VBR_mean_bitrate_kbps(gfp, gfp->brate);\n            /* second, set parameters depending on bitrate */\n            (void) apply_preset(gfp, gfp->VBR_mean_bitrate_kbps, 0);\n            gfp->VBR = vbrmode;\n\n            if (vbrmode == vbr_off) {\n                gfc->iteration_loop = CBR_iteration_loop;\n            }\n            else {\n                gfc->iteration_loop = ABR_iteration_loop;\n            }\n            break;\n        }\n    }\n\n    /*initialize default values common for all modes */\n\n    gfc->sv_qnt.mask_adjust = gfp->maskingadjust;\n    gfc->sv_qnt.mask_adjust_short = gfp->maskingadjust_short;\n\n    /*  just another daily changing developer switch  */\n    if (gfp->tune) {\n        gfc->sv_qnt.mask_adjust += gfp->tune_value_a;\n        gfc->sv_qnt.mask_adjust_short += gfp->tune_value_a;\n    }\n\n\n    if (gfp->VBR != vbr_off) { /* choose a min/max bitrate for VBR */\n        /* if the user didn't specify VBR_max_bitrate: */\n        cfg->vbr_min_bitrate_index = 1; /* default: allow   8 kbps (MPEG-2) or  32 kbps (MPEG-1) */\n        cfg->vbr_max_bitrate_index = 14; /* default: allow 160 kbps (MPEG-2) or 320 kbps (MPEG-1) */\n        if (cfg->samplerate_out < 16000)\n            cfg->vbr_max_bitrate_index = 8; /* default: allow 64 kbps (MPEG-2.5) */\n        if (gfp->VBR_min_bitrate_kbps) {\n            gfp->VBR_min_bitrate_kbps =\n                FindNearestBitrate(gfp->VBR_min_bitrate_kbps, cfg->version, cfg->samplerate_out);\n            cfg->vbr_min_bitrate_index =\n                BitrateIndex(gfp->VBR_min_bitrate_kbps, cfg->version, cfg->samplerate_out);\n            if (cfg->vbr_min_bitrate_index < 0)\n                return -1;\n        }\n        if (gfp->VBR_max_bitrate_kbps) {\n            gfp->VBR_max_bitrate_kbps =\n                FindNearestBitrate(gfp->VBR_max_bitrate_kbps, cfg->version, cfg->samplerate_out);\n            cfg->vbr_max_bitrate_index =\n                BitrateIndex(gfp->VBR_max_bitrate_kbps, cfg->version, cfg->samplerate_out);\n            if (cfg->vbr_max_bitrate_index < 0)\n                return -1;\n        }\n        gfp->VBR_min_bitrate_kbps = bitrate_table[cfg->version][cfg->vbr_min_bitrate_index];\n        gfp->VBR_max_bitrate_kbps = bitrate_table[cfg->version][cfg->vbr_max_bitrate_index];\n        gfp->VBR_mean_bitrate_kbps =\n            Min(bitrate_table[cfg->version][cfg->vbr_max_bitrate_index],\n                gfp->VBR_mean_bitrate_kbps);\n        gfp->VBR_mean_bitrate_kbps =\n            Max(bitrate_table[cfg->version][cfg->vbr_min_bitrate_index],\n                gfp->VBR_mean_bitrate_kbps);\n    }\n\n    cfg->preset = gfp->preset;\n    cfg->write_lame_tag = gfp->write_lame_tag;\n    cfg->vbr = gfp->VBR;\n    gfc->sv_qnt.substep_shaping = gfp->substep_shaping;\n    cfg->noise_shaping = gfp->noise_shaping;\n    cfg->subblock_gain = gfp->subblock_gain;\n    cfg->use_best_huffman = gfp->use_best_huffman;\n    cfg->avg_bitrate = gfp->brate;\n    cfg->vbr_avg_bitrate_kbps = gfp->VBR_mean_bitrate_kbps;\n    cfg->compression_ratio = gfp->compression_ratio;\n\n    /* initialize internal qval settings */\n    lame_init_qval(gfp);\n\n\n    /*  automatic ATH adjustment on\n     */\n    if (gfp->athaa_type < 0)\n        gfc->ATH->use_adjust = 3;\n    else\n        gfc->ATH->use_adjust = gfp->athaa_type;\n\n\n    /* initialize internal adaptive ATH settings  -jd */\n    gfc->ATH->aa_sensitivity_p = pow(10.0, gfp->athaa_sensitivity / -10.0);\n\n\n    if (gfp->short_blocks == short_block_not_set) {\n        gfp->short_blocks = short_block_allowed;\n    }\n\n    /*Note Jan/2003: Many hardware decoders cannot handle short blocks in regular\n       stereo mode unless they are coupled (same type in both channels)\n       it is a rare event (1 frame per min. or so) that LAME would use\n       uncoupled short blocks, so lets turn them off until we decide\n       how to handle this.  No other encoders allow uncoupled short blocks,\n       even though it is in the standard.  */\n    /* rh 20040217: coupling makes no sense for mono and dual-mono streams\n     */\n    if (gfp->short_blocks == short_block_allowed\n        && (cfg->mode == JOINT_STEREO || cfg->mode == STEREO)) {\n        gfp->short_blocks = short_block_coupled;\n    }\n\n    cfg->short_blocks = gfp->short_blocks;\n\n\n    if (lame_get_quant_comp(gfp) < 0)\n        (void) lame_set_quant_comp(gfp, 1);\n    if (lame_get_quant_comp_short(gfp) < 0)\n        (void) lame_set_quant_comp_short(gfp, 0);\n\n    if (lame_get_msfix(gfp) < 0)\n        lame_set_msfix(gfp, 0);\n\n    /* select psychoacoustic model */\n    (void) lame_set_exp_nspsytune(gfp, lame_get_exp_nspsytune(gfp) | 1);\n\n    if (gfp->ATHtype < 0)\n        gfp->ATHtype = 4;\n\n    if (gfp->ATHcurve < 0)\n        gfp->ATHcurve = 4;\n\n    if (gfp->interChRatio < 0)\n        gfp->interChRatio = 0;\n\n    if (gfp->useTemporal < 0)\n        gfp->useTemporal = 1; /* on by default */\n\n\n    cfg->interChRatio = gfp->interChRatio;\n    cfg->msfix = gfp->msfix;\n    cfg->ATH_offset_db = 0-gfp->ATH_lower_db;\n    cfg->ATH_offset_factor = powf(10.f, cfg->ATH_offset_db * 0.1f);\n    cfg->ATHcurve = gfp->ATHcurve;\n    cfg->ATHtype = gfp->ATHtype;\n    cfg->ATHonly = gfp->ATHonly;\n    cfg->ATHshort = gfp->ATHshort;\n    cfg->noATH = gfp->noATH;\n\n    cfg->quant_comp = gfp->quant_comp;\n    cfg->quant_comp_short = gfp->quant_comp_short;\n\n    cfg->use_temporal_masking_effect = gfp->useTemporal;\n    cfg->use_safe_joint_stereo = gfp->exp_nspsytune & 2;\n    {\n        cfg->adjust_bass_db = (gfp->exp_nspsytune >> 2) & 63;\n        if (cfg->adjust_bass_db >= 32.f)\n            cfg->adjust_bass_db -= 64.f;\n        cfg->adjust_bass_db *= 0.25f;\n\n        cfg->adjust_alto_db = (gfp->exp_nspsytune >> 8) & 63;\n        if (cfg->adjust_alto_db >= 32.f)\n            cfg->adjust_alto_db -= 64.f;\n        cfg->adjust_alto_db *= 0.25f;\n\n        cfg->adjust_treble_db = (gfp->exp_nspsytune >> 14) & 63;\n        if (cfg->adjust_treble_db >= 32.f)\n            cfg->adjust_treble_db -= 64.f;\n        cfg->adjust_treble_db *= 0.25f;\n\n        /*  to be compatible with Naoki's original code, the next 6 bits\n         *  define only the amount of changing treble for sfb21 */\n        cfg->adjust_sfb21_db = (gfp->exp_nspsytune >> 20) & 63;\n        if (cfg->adjust_sfb21_db >= 32.f)\n            cfg->adjust_sfb21_db -= 64.f;\n        cfg->adjust_sfb21_db *= 0.25f;\n        cfg->adjust_sfb21_db += cfg->adjust_treble_db;\n    }\n\n    /* Setting up the PCM input data transform matrix, to apply \n     * user defined re-scaling, and or two-to-one channel downmix.\n     */\n    {\n        FLOAT   m[2][2] = { {1.0f, 0.0f}, {0.0f, 1.0f} };\n\n        /* user selected scaling of the samples */\n        m[0][0] *= gfp->scale;\n        m[0][1] *= gfp->scale;\n        m[1][0] *= gfp->scale;\n        m[1][1] *= gfp->scale;\n        /* user selected scaling of the channel 0 (left) samples */\n        m[0][0] *= gfp->scale_left;\n        m[0][1] *= gfp->scale_left;\n        /* user selected scaling of the channel 1 (right) samples */\n        m[1][0] *= gfp->scale_right;\n        m[1][1] *= gfp->scale_right;\n        /* Downsample to Mono if 2 channels in and 1 channel out */\n        if (cfg->channels_in == 2 && cfg->channels_out == 1) {\n            m[0][0] = 0.5f * (m[0][0] + m[1][0]);\n            m[0][1] = 0.5f * (m[0][1] + m[1][1]);\n            m[1][0] = 0;\n            m[1][1] = 0;\n        }\n        cfg->pcm_transform[0][0] = m[0][0];\n        cfg->pcm_transform[0][1] = m[0][1];\n        cfg->pcm_transform[1][0] = m[1][0];\n        cfg->pcm_transform[1][1] = m[1][1];\n    }\n\n    /* padding method as described in\n     * \"MPEG-Layer3 / Bitstream Syntax and Decoding\"\n     * by Martin Sieler, Ralph Sperschneider\n     *\n     * note: there is no padding for the very first frame\n     *\n     * Robert Hegemann 2000-06-22\n     */\n    gfc->sv_enc.slot_lag = gfc->sv_enc.frac_SpF = 0;\n    if (cfg->vbr == vbr_off)\n        gfc->sv_enc.slot_lag = gfc->sv_enc.frac_SpF\n            = ((cfg->version + 1) * 72000L * cfg->avg_bitrate) % cfg->samplerate_out;\n\n    (void) lame_init_bitstream(gfp);\n\n    iteration_init(gfc);\n    (void) psymodel_init(gfp);\n\n    cfg->buffer_constraint = get_max_frame_buffer_size_by_constraint(cfg, gfp->strict_ISO);\n    return 0;\n}\n\nstatic void\nconcatSep(char* dest, char const* sep, char const* str)\n{\n    if (*dest != 0) strcat(dest, sep);\n    strcat(dest, str);\n}\n\n/*\n *  print_config\n *\n *  Prints some selected information about the coding parameters via\n *  the macro command MSGF(), which is currently mapped to lame_errorf\n *  (reports via a error function?), which is a printf-like function\n *  for <stderr>.\n */\n\nvoid\nlame_print_config(const lame_global_flags * gfp)\n{\n    lame_internal_flags const *const gfc = gfp->internal_flags;\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    double const out_samplerate = cfg->samplerate_out;\n    double const in_samplerate = cfg->samplerate_in;\n\n    MSGF(gfc, \"LAME %s %s (%s)\\n\", get_lame_version(), get_lame_os_bitness(), get_lame_url());\n\n#if (LAME_ALPHA_VERSION)\n    MSGF(gfc, \"warning: alpha versions should be used for testing only\\n\");\n#endif\n    if (gfc->CPU_features.MMX\n        || gfc->CPU_features.AMD_3DNow || gfc->CPU_features.SSE || gfc->CPU_features.SSE2) {\n        char    text[256] = { 0 };\n        int     fft_asm_used = 0;\n#ifdef HAVE_NASM\n        if (gfc->CPU_features.AMD_3DNow) {\n            fft_asm_used = 1;\n        }\n        else if (gfc->CPU_features.SSE) {\n            fft_asm_used = 2;\n        }\n#else\n# if defined( HAVE_XMMINTRIN_H ) && defined( MIN_ARCH_SSE )\n        {\n            fft_asm_used = 3;\n        }\n# endif\n#endif\n        if (gfc->CPU_features.MMX) {\n#ifdef MMX_choose_table\n            concatSep(text, \", \", \"MMX (ASM used)\");\n#else\n            concatSep(text, \", \", \"MMX\");\n#endif\n        }\n        if (gfc->CPU_features.AMD_3DNow) {\n            concatSep(text, \", \", (fft_asm_used == 1) ? \"3DNow! (ASM used)\" : \"3DNow!\");\n        }\n        if (gfc->CPU_features.SSE) {\n#if defined(HAVE_XMMINTRIN_H)\n            concatSep(text, \", \", \"SSE (ASM used)\");\n#else\n            concatSep(text, \", \", (fft_asm_used == 2) ? \"SSE (ASM used)\" : \"SSE\");\n#endif\n        }\n        if (gfc->CPU_features.SSE2) {\n            concatSep(text, \", \", (fft_asm_used == 3) ? \"SSE2 (ASM used)\" : \"SSE2\");\n        }\n        MSGF(gfc, \"CPU features: %s\\n\", text);\n    }\n\n    if (cfg->channels_in == 2 && cfg->channels_out == 1 /* mono */ ) {\n        MSGF(gfc, \"Autoconverting from stereo to mono. Setting encoding to mono mode.\\n\");\n    }\n\n    if (isResamplingNecessary(cfg)) {\n        MSGF(gfc, \"Resampling:  input %g kHz  output %g kHz\\n\",\n             1.e-3 * in_samplerate, 1.e-3 * out_samplerate);\n    }\n\n    if (cfg->highpass2 > 0.)\n        MSGF(gfc,\n             \"Using polyphase highpass filter, transition band: %5.0f Hz - %5.0f Hz\\n\",\n             0.5 * cfg->highpass1 * out_samplerate, 0.5 * cfg->highpass2 * out_samplerate);\n    if (0. < cfg->lowpass1 || 0. < cfg->lowpass2) {\n        MSGF(gfc,\n             \"Using polyphase lowpass filter, transition band: %5.0f Hz - %5.0f Hz\\n\",\n             0.5 * cfg->lowpass1 * out_samplerate, 0.5 * cfg->lowpass2 * out_samplerate);\n    }\n    else {\n        MSGF(gfc, \"polyphase lowpass filter disabled\\n\");\n    }\n\n    if (cfg->free_format) {\n        MSGF(gfc, \"Warning: many decoders cannot handle free format bitstreams\\n\");\n        if (cfg->avg_bitrate > 320) {\n            MSGF(gfc,\n                 \"Warning: many decoders cannot handle free format bitrates >320 kbps (see documentation)\\n\");\n        }\n    }\n}\n\n\n/**     rh:\n *      some pretty printing is very welcome at this point!\n *      so, if someone is willing to do so, please do it!\n *      add more, if you see more...\n */\nvoid\nlame_print_internals(const lame_global_flags * gfp)\n{\n    lame_internal_flags const *const gfc = gfp->internal_flags;\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    const char *pc = \"\";\n\n    /*  compiler/processor optimizations, operational, etc.\n     */\n    MSGF(gfc, \"\\nmisc:\\n\\n\");\n\n    MSGF(gfc, \"\\tscaling: %g\\n\", gfp->scale);\n    MSGF(gfc, \"\\tch0 (left) scaling: %g\\n\", gfp->scale_left);\n    MSGF(gfc, \"\\tch1 (right) scaling: %g\\n\", gfp->scale_right);\n    switch (cfg->use_best_huffman) {\n    default:\n        pc = \"normal\";\n        break;\n    case 1:\n        pc = \"best (outside loop)\";\n        break;\n    case 2:\n        pc = \"best (inside loop, slow)\";\n        break;\n    }\n    MSGF(gfc, \"\\thuffman search: %s\\n\", pc);\n    MSGF(gfc, \"\\texperimental Y=%d\\n\", gfp->experimentalY);\n    MSGF(gfc, \"\\t...\\n\");\n\n    /*  everything controlling the stream format\n     */\n    MSGF(gfc, \"\\nstream format:\\n\\n\");\n    switch (cfg->version) {\n    case 0:\n        pc = \"2.5\";\n        break;\n    case 1:\n        pc = \"1\";\n        break;\n    case 2:\n        pc = \"2\";\n        break;\n    default:\n        pc = \"?\";\n        break;\n    }\n    MSGF(gfc, \"\\tMPEG-%s Layer 3\\n\", pc);\n    switch (cfg->mode) {\n    case JOINT_STEREO:\n        pc = \"joint stereo\";\n        break;\n    case STEREO:\n        pc = \"stereo\";\n        break;\n    case DUAL_CHANNEL:\n        pc = \"dual channel\";\n        break;\n    case MONO:\n        pc = \"mono\";\n        break;\n    case NOT_SET:\n        pc = \"not set (error)\";\n        break;\n    default:\n        pc = \"unknown (error)\";\n        break;\n    }\n    MSGF(gfc, \"\\t%d channel - %s\\n\", cfg->channels_out, pc);\n\n    switch (cfg->vbr) {\n    case vbr_off:\n        pc = \"off\";\n        break;\n    default:\n        pc = \"all\";\n        break;\n    }\n    MSGF(gfc, \"\\tpadding: %s\\n\", pc);\n\n    if (vbr_default == cfg->vbr)\n        pc = \"(default)\";\n    else if (cfg->free_format)\n        pc = \"(free format)\";\n    else\n        pc = \"\";\n    switch (cfg->vbr) {\n    case vbr_off:\n        MSGF(gfc, \"\\tconstant bitrate - CBR %s\\n\", pc);\n        break;\n    case vbr_abr:\n        MSGF(gfc, \"\\tvariable bitrate - ABR %s\\n\", pc);\n        break;\n    case vbr_rh:\n        MSGF(gfc, \"\\tvariable bitrate - VBR rh %s\\n\", pc);\n        break;\n    case vbr_mt:\n        MSGF(gfc, \"\\tvariable bitrate - VBR mt %s\\n\", pc);\n        break;\n    case vbr_mtrh:\n        MSGF(gfc, \"\\tvariable bitrate - VBR mtrh %s\\n\", pc);\n        break;\n    default:\n        MSGF(gfc, \"\\t ?? oops, some new one ?? \\n\");\n        break;\n    }\n    if (cfg->write_lame_tag)\n        MSGF(gfc, \"\\tusing LAME Tag\\n\");\n    MSGF(gfc, \"\\t...\\n\");\n\n    /*  everything controlling psychoacoustic settings, like ATH, etc.\n     */\n    MSGF(gfc, \"\\npsychoacoustic:\\n\\n\");\n\n    switch (cfg->short_blocks) {\n    default:\n    case short_block_not_set:\n        pc = \"?\";\n        break;\n    case short_block_allowed:\n        pc = \"allowed\";\n        break;\n    case short_block_coupled:\n        pc = \"channel coupled\";\n        break;\n    case short_block_dispensed:\n        pc = \"dispensed\";\n        break;\n    case short_block_forced:\n        pc = \"forced\";\n        break;\n    }\n    MSGF(gfc, \"\\tusing short blocks: %s\\n\", pc);\n    MSGF(gfc, \"\\tsubblock gain: %d\\n\", cfg->subblock_gain);\n    MSGF(gfc, \"\\tadjust masking: %g dB\\n\", gfc->sv_qnt.mask_adjust);\n    MSGF(gfc, \"\\tadjust masking short: %g dB\\n\", gfc->sv_qnt.mask_adjust_short);\n    MSGF(gfc, \"\\tquantization comparison: %d\\n\", cfg->quant_comp);\n    MSGF(gfc, \"\\t ^ comparison short blocks: %d\\n\", cfg->quant_comp_short);\n    MSGF(gfc, \"\\tnoise shaping: %d\\n\", cfg->noise_shaping);\n    MSGF(gfc, \"\\t ^ amplification: %d\\n\", cfg->noise_shaping_amp);\n    MSGF(gfc, \"\\t ^ stopping: %d\\n\", cfg->noise_shaping_stop);\n\n    pc = \"using\";\n    if (cfg->ATHshort)\n        pc = \"the only masking for short blocks\";\n    if (cfg->ATHonly)\n        pc = \"the only masking\";\n    if (cfg->noATH)\n        pc = \"not used\";\n    MSGF(gfc, \"\\tATH: %s\\n\", pc);\n    MSGF(gfc, \"\\t ^ type: %d\\n\", cfg->ATHtype);\n    MSGF(gfc, \"\\t ^ shape: %g%s\\n\", cfg->ATHcurve, \" (only for type 4)\");\n    MSGF(gfc, \"\\t ^ level adjustement: %g dB\\n\", cfg->ATH_offset_db);\n    MSGF(gfc, \"\\t ^ adjust type: %d\\n\", gfc->ATH->use_adjust);\n    MSGF(gfc, \"\\t ^ adjust sensitivity power: %f\\n\", gfc->ATH->aa_sensitivity_p);\n\n    MSGF(gfc, \"\\texperimental psy tunings by Naoki Shibata\\n\");\n    MSGF(gfc, \"\\t   adjust masking bass=%g dB, alto=%g dB, treble=%g dB, sfb21=%g dB\\n\",\n         10 * log10(gfc->sv_qnt.longfact[0]),\n         10 * log10(gfc->sv_qnt.longfact[7]),\n         10 * log10(gfc->sv_qnt.longfact[14]), 10 * log10(gfc->sv_qnt.longfact[21]));\n\n    pc = cfg->use_temporal_masking_effect ? \"yes\" : \"no\";\n    MSGF(gfc, \"\\tusing temporal masking effect: %s\\n\", pc);\n    MSGF(gfc, \"\\tinterchannel masking ratio: %g\\n\", cfg->interChRatio);\n    MSGF(gfc, \"\\t...\\n\");\n\n    /*  that's all ?\n     */\n    MSGF(gfc, \"\\n\");\n    return;\n}\n\n\nstatic void\nsave_gain_values(lame_internal_flags * gfc)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    RpgStateVar_t const *const rsv = &gfc->sv_rpg;\n    RpgResult_t *const rov = &gfc->ov_rpg;\n    /* save the ReplayGain value */\n    if (cfg->findReplayGain) {\n        FLOAT const RadioGain = (FLOAT) GetTitleGain(rsv->rgdata);\n        if (NEQ(RadioGain, GAIN_NOT_ENOUGH_SAMPLES)) {\n            rov->RadioGain = (int) floor(RadioGain * 10.0 + 0.5); /* round to nearest */\n        }\n        else {\n            rov->RadioGain = 0;\n        }\n    }\n\n    /* find the gain and scale change required for no clipping */\n    if (cfg->findPeakSample) {\n        rov->noclipGainChange = (int) ceil(log10(rov->PeakSample / 32767.0) * 20.0 * 10.0); /* round up */\n\n        if (rov->noclipGainChange > 0) { /* clipping occurs */\n            rov->noclipScale = floor((32767.0f / rov->PeakSample) * 100.0f) / 100.0f; /* round down */\n        }\n        else            /* no clipping */\n            rov->noclipScale = -1.0f;\n    }\n}\n\n\n\nstatic int\nupdate_inbuffer_size(lame_internal_flags * gfc, const int nsamples)\n{\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    if (esv->in_buffer_0 == 0 || esv->in_buffer_nsamples < nsamples) {\n        if (esv->in_buffer_0) {\n            free(esv->in_buffer_0);\n        }\n        if (esv->in_buffer_1) {\n            free(esv->in_buffer_1);\n        }\n        esv->in_buffer_0 = calloc(nsamples, sizeof(sample_t));\n        esv->in_buffer_1 = calloc(nsamples, sizeof(sample_t));\n        esv->in_buffer_nsamples = nsamples;\n    }\n    if (esv->in_buffer_0 == NULL || esv->in_buffer_1 == NULL) {\n        if (esv->in_buffer_0) {\n            free(esv->in_buffer_0);\n        }\n        if (esv->in_buffer_1) {\n            free(esv->in_buffer_1);\n        }\n        esv->in_buffer_0 = 0;\n        esv->in_buffer_1 = 0;\n        esv->in_buffer_nsamples = 0;\n        ERRORF(gfc, \"Error: can't allocate in_buffer buffer\\n\");\n        return -2;\n    }\n    return 0;\n}\n\n\nstatic int\ncalcNeeded(SessionConfig_t const * cfg)\n{\n    int     mf_needed;\n    int     pcm_samples_per_frame = 576 * cfg->mode_gr;\n\n    /* some sanity checks */\n#if ENCDELAY < MDCTDELAY\n# error ENCDELAY is less than MDCTDELAY, see encoder.h\n#endif\n#if FFTOFFSET > BLKSIZE\n# error FFTOFFSET is greater than BLKSIZE, see encoder.h\n#endif\n\n    mf_needed = BLKSIZE + pcm_samples_per_frame - FFTOFFSET; /* amount needed for FFT */\n    /*mf_needed = Max(mf_needed, 286 + 576 * (1 + gfc->mode_gr)); */\n    mf_needed = Max(mf_needed, 512 + pcm_samples_per_frame - 32);\n\n    assert(MFSIZE >= mf_needed);\n    \n    return mf_needed;\n}\n\n\n/*\n * THE MAIN LAME ENCODING INTERFACE\n * mt 3/00\n *\n * input pcm data, output (maybe) mp3 frames.\n * This routine handles all buffering, resampling and filtering for you.\n * The required mp3buffer_size can be computed from num_samples,\n * samplerate and encoding rate, but here is a worst case estimate:\n *\n * mp3buffer_size in bytes = 1.25*num_samples + 7200\n *\n * return code = number of bytes output in mp3buffer.  can be 0\n *\n * NOTE: this routine uses LAME's internal PCM data representation,\n * 'sample_t'.  It should not be used by any application.\n * applications should use lame_encode_buffer(),\n *                         lame_encode_buffer_float()\n *                         lame_encode_buffer_int()\n * etc... depending on what type of data they are working with.\n*/\nstatic int\nlame_encode_buffer_sample_t(lame_internal_flags * gfc,\n                            int nsamples, unsigned char *mp3buf, const int mp3buf_size)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    int     pcm_samples_per_frame = 576 * cfg->mode_gr;\n    int     mp3size = 0, ret, i, ch, mf_needed;\n    int     mp3out;\n    sample_t *mfbuf[2];\n    sample_t *in_buffer[2];\n\n    if (gfc->class_id != LAME_ID)\n        return -3;\n\n    if (nsamples == 0)\n        return 0;\n\n    /* copy out any tags that may have been written into bitstream */\n    mp3out = copy_buffer(gfc, mp3buf, mp3buf_size, 0);\n    if (mp3out < 0)\n        return mp3out;  /* not enough buffer space */\n    mp3buf += mp3out;\n    mp3size += mp3out;\n\n    in_buffer[0] = esv->in_buffer_0;\n    in_buffer[1] = esv->in_buffer_1;\n\n    mf_needed = calcNeeded(cfg);\n\n    mfbuf[0] = esv->mfbuf[0];\n    mfbuf[1] = esv->mfbuf[1];\n\n    while (nsamples > 0) {\n        sample_t const *in_buffer_ptr[2];\n        int     n_in = 0;    /* number of input samples processed with fill_buffer */\n        int     n_out = 0;   /* number of samples output with fill_buffer */\n        /* n_in <> n_out if we are resampling */\n\n        in_buffer_ptr[0] = in_buffer[0];\n        in_buffer_ptr[1] = in_buffer[1];\n        /* copy in new samples into mfbuf, with resampling */\n        fill_buffer(gfc, mfbuf, &in_buffer_ptr[0], nsamples, &n_in, &n_out);\n\n        /* compute ReplayGain of resampled input if requested */\n        if (cfg->findReplayGain && !cfg->decode_on_the_fly)\n            if (AnalyzeSamples\n                (gfc->sv_rpg.rgdata, &mfbuf[0][esv->mf_size], &mfbuf[1][esv->mf_size], n_out,\n                 cfg->channels_out) == GAIN_ANALYSIS_ERROR)\n                return -6;\n\n\n\n        /* update in_buffer counters */\n        nsamples -= n_in;\n        in_buffer[0] += n_in;\n        if (cfg->channels_out == 2)\n            in_buffer[1] += n_in;\n\n        /* update mfbuf[] counters */\n        esv->mf_size += n_out;\n        assert(esv->mf_size <= MFSIZE);\n        \n        /* lame_encode_flush may have set gfc->mf_sample_to_encode to 0\n         * so we have to reinitialize it here when that happened.\n         */\n        if (esv->mf_samples_to_encode < 1) {\n            esv->mf_samples_to_encode = ENCDELAY + POSTDELAY;\n        }        \n        esv->mf_samples_to_encode += n_out;\n\n\n        if (esv->mf_size >= mf_needed) {\n            /* encode the frame.  */\n            /* mp3buf              = pointer to current location in buffer */\n            /* mp3buf_size         = size of original mp3 output buffer */\n            /*                     = 0 if we should not worry about the */\n            /*                       buffer size because calling program is  */\n            /*                       to lazy to compute it */\n            /* mp3size             = size of data written to buffer so far */\n            /* mp3buf_size-mp3size = amount of space avalable  */\n\n            int     buf_size = mp3buf_size - mp3size;\n            if (mp3buf_size == 0)\n                buf_size = 0;\n\n            ret = lame_encode_mp3_frame(gfc, mfbuf[0], mfbuf[1], mp3buf, buf_size);\n\n            if (ret < 0)\n                return ret;\n            mp3buf += ret;\n            mp3size += ret;\n\n            /* shift out old samples */\n            esv->mf_size -= pcm_samples_per_frame;\n            esv->mf_samples_to_encode -= pcm_samples_per_frame;\n            for (ch = 0; ch < cfg->channels_out; ch++)\n                for (i = 0; i < esv->mf_size; i++)\n                    mfbuf[ch][i] = mfbuf[ch][i + pcm_samples_per_frame];\n        }\n    }\n    assert(nsamples == 0);\n\n    return mp3size;\n}\n\nenum PCMSampleType \n{   pcm_short_type\n,   pcm_int_type\n,   pcm_long_type\n,   pcm_float_type\n,   pcm_double_type\n};\n\nstatic void\nlame_copy_inbuffer(lame_internal_flags* gfc, \n                   void const* l, void const* r, int nsamples,\n                   enum PCMSampleType pcm_type, int jump, FLOAT s)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    sample_t* ib0 = esv->in_buffer_0;\n    sample_t* ib1 = esv->in_buffer_1;\n    FLOAT   m[2][2];\n\n    /* Apply user defined re-scaling */\n    m[0][0] = s * cfg->pcm_transform[0][0];\n    m[0][1] = s * cfg->pcm_transform[0][1];\n    m[1][0] = s * cfg->pcm_transform[1][0];\n    m[1][1] = s * cfg->pcm_transform[1][1];\n\n    /* make a copy of input buffer, changing type to sample_t */\n#define COPY_AND_TRANSFORM(T) \\\n{ \\\n    T const *bl = l, *br = r; \\\n    int     i; \\\n    for (i = 0; i < nsamples; i++) { \\\n        sample_t const xl = *bl; \\\n        sample_t const xr = *br; \\\n        sample_t const u = xl * m[0][0] + xr * m[0][1]; \\\n        sample_t const v = xl * m[1][0] + xr * m[1][1]; \\\n        ib0[i] = u; \\\n        ib1[i] = v; \\\n        bl += jump; \\\n        br += jump; \\\n    } \\\n}\n    switch ( pcm_type ) {\n    case pcm_short_type: \n        COPY_AND_TRANSFORM(short int);\n        break;\n    case pcm_int_type:\n        COPY_AND_TRANSFORM(int);\n        break;\n    case pcm_long_type:\n        COPY_AND_TRANSFORM(long int);\n        break;\n    case pcm_float_type:\n        COPY_AND_TRANSFORM(float);\n        break;\n    case pcm_double_type:\n        COPY_AND_TRANSFORM(double);\n        break;\n    }\n}\n\n\nstatic int\nlame_encode_buffer_template(lame_global_flags * gfp,\n                            void const* buffer_l, void const* buffer_r, const int nsamples,\n                            unsigned char *mp3buf, const int mp3buf_size, enum PCMSampleType pcm_type, int aa, FLOAT norm)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            SessionConfig_t const *const cfg = &gfc->cfg;\n\n            if (nsamples == 0)\n                return 0;\n\n            if (update_inbuffer_size(gfc, nsamples) != 0) {\n                return -2;\n            }\n            /* make a copy of input buffer, changing type to sample_t */\n            if (cfg->channels_in > 1) {\n                if (buffer_l == 0 || buffer_r == 0) {\n                    return 0;\n                }\n                lame_copy_inbuffer(gfc, buffer_l, buffer_r, nsamples, pcm_type, aa, norm);\n            }\n            else {\n                if (buffer_l == 0) {\n                    return 0;\n                }\n                lame_copy_inbuffer(gfc, buffer_l, buffer_l, nsamples, pcm_type, aa, norm);\n            }\n\n            return lame_encode_buffer_sample_t(gfc, nsamples, mp3buf, mp3buf_size);\n        }\n    }\n    return -3;\n}\n\nint\nlame_encode_buffer(lame_global_flags * gfp,\n                   const short int pcm_l[], const short int pcm_r[], const int nsamples,\n                   unsigned char *mp3buf, const int mp3buf_size)\n{\n    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_short_type, 1, 1.0);\n}\n\n\nint\nlame_encode_buffer_float(lame_global_flags * gfp,\n                         const float pcm_l[], const float pcm_r[], const int nsamples,\n                         unsigned char *mp3buf, const int mp3buf_size)\n{\n    /* input is assumed to be normalized to +/- 32768 for full scale */\n    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_float_type, 1, 1.0);\n}\n\n\nint\nlame_encode_buffer_ieee_float(lame_t gfp,\n                         const float pcm_l[], const float pcm_r[], const int nsamples,\n                         unsigned char *mp3buf, const int mp3buf_size)\n{\n    /* input is assumed to be normalized to +/- 1.0 for full scale */\n    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_float_type, 1, 32767.0);\n}\n\n\nint\nlame_encode_buffer_interleaved_ieee_float(lame_t gfp,\n                         const float pcm[], const int nsamples,\n                         unsigned char *mp3buf, const int mp3buf_size)\n{\n    /* input is assumed to be normalized to +/- 1.0 for full scale */\n    return lame_encode_buffer_template(gfp, pcm, pcm+1, nsamples, mp3buf, mp3buf_size, pcm_float_type, 2, 32767.0);\n}\n\n\nint\nlame_encode_buffer_ieee_double(lame_t gfp,\n                         const double pcm_l[], const double pcm_r[], const int nsamples,\n                         unsigned char *mp3buf, const int mp3buf_size)\n{\n    /* input is assumed to be normalized to +/- 1.0 for full scale */\n    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_double_type, 1, 32767.0);\n}\n\n\nint\nlame_encode_buffer_interleaved_ieee_double(lame_t gfp,\n                         const double pcm[], const int nsamples,\n                         unsigned char *mp3buf, const int mp3buf_size)\n{\n    /* input is assumed to be normalized to +/- 1.0 for full scale */\n    return lame_encode_buffer_template(gfp, pcm, pcm+1, nsamples, mp3buf, mp3buf_size, pcm_double_type, 2, 32767.0);\n}\n\n\nint\nlame_encode_buffer_int(lame_global_flags * gfp,\n                       const int pcm_l[], const int pcm_r[], const int nsamples,\n                       unsigned char *mp3buf, const int mp3buf_size)\n{\n    /* input is assumed to be normalized to +/- MAX_INT for full scale */\n    FLOAT const norm = (1.0 / (1L << (8 * sizeof(int) - 16)));\n    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_int_type, 1, norm);\n}\n\n\nint\nlame_encode_buffer_long2(lame_global_flags * gfp,\n                         const long pcm_l[],  const long pcm_r[], const int nsamples,\n                         unsigned char *mp3buf, const int mp3buf_size)\n{\n    /* input is assumed to be normalized to +/- MAX_LONG for full scale */\n    FLOAT const norm = (1.0 / (1L << (8 * sizeof(long) - 16)));\n    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_long_type, 1, norm);\n}\n\n\nint\nlame_encode_buffer_long(lame_global_flags * gfp,\n                        const long pcm_l[], const long pcm_r[], const int nsamples,\n                        unsigned char *mp3buf, const int mp3buf_size)\n{\n    /* input is assumed to be normalized to +/- 32768 for full scale */\n    return lame_encode_buffer_template(gfp, pcm_l, pcm_r, nsamples, mp3buf, mp3buf_size, pcm_long_type, 1, 1.0);\n}\n\n\n\nint\nlame_encode_buffer_interleaved(lame_global_flags * gfp,\n                               short int pcm[], int nsamples,\n                               unsigned char *mp3buf, int mp3buf_size)\n{\n    /* input is assumed to be normalized to +/- MAX_SHORT for full scale */\n    return lame_encode_buffer_template(gfp, pcm, pcm+1, nsamples, mp3buf, mp3buf_size, pcm_short_type, 2, 1.0);\n}\n\n\n\n\n/*****************************************************************\n Flush mp3 buffer, pad with ancillary data so last frame is complete.\n Reset reservoir size to 0\n but keep all PCM samples and MDCT data in memory\n This option is used to break a large file into several mp3 files\n that when concatenated together will decode with no gaps\n Because we set the reservoir=0, they will also decode seperately\n with no errors.\n*********************************************************************/\nint\nlame_encode_flush_nogap(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)\n{\n    int     rc = -3;\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            flush_bitstream(gfc);\n            rc = copy_buffer(gfc, mp3buffer, mp3buffer_size, 1);\n            save_gain_values(gfc);\n        }\n    }\n    return rc;\n}\n\n\n/* called by lame_init_params.  You can also call this after flush_nogap\n   if you want to write new id3v2 and Xing VBR tags into the bitstream */\nint\nlame_init_bitstream(lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags *const gfc = gfp->internal_flags;\n        if (gfc != 0) {\n            gfc->ov_enc.frame_number = 0;\n\n            if (gfp->write_id3tag_automatic) {\n                (void) id3tag_write_v2(gfp);\n            }\n            /* initialize histogram data optionally used by frontend */\n            memset(gfc->ov_enc.bitrate_channelmode_hist, 0,\n                   sizeof(gfc->ov_enc.bitrate_channelmode_hist));\n            memset(gfc->ov_enc.bitrate_blocktype_hist, 0,\n                   sizeof(gfc->ov_enc.bitrate_blocktype_hist));\n\n            gfc->ov_rpg.PeakSample = 0.0;\n\n            /* Write initial VBR Header to bitstream and init VBR data */\n            if (gfc->cfg.write_lame_tag)\n                (void) InitVbrTag(gfp);\n\n\n            return 0;\n        }\n    }\n    return -3;\n}\n\n\n/*****************************************************************/\n/* flush internal PCM sample buffers, then mp3 buffers           */\n/* then write id3 v1 tags into bitstream.                        */\n/*****************************************************************/\n\nint\nlame_encode_flush(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)\n{\n    lame_internal_flags *gfc;\n    SessionConfig_t const *cfg;\n    EncStateVar_t *esv;\n    short int buffer[2][1152];\n    int     imp3 = 0, mp3count, mp3buffer_size_remaining;\n\n    /* we always add POSTDELAY=288 padding to make sure granule with real\n     * data can be complety decoded (because of 50% overlap with next granule */\n    int     end_padding;\n    int     frames_left;\n    int     samples_to_encode;\n    int     pcm_samples_per_frame;\n    int     mf_needed;\n    int     is_resampling_necessary;\n    double  resample_ratio = 1;\n\n    if (!is_lame_global_flags_valid(gfp)) {\n        return -3;\n    }\n    gfc = gfp->internal_flags;\n    if (!is_lame_internal_flags_valid(gfc)) {\n        return -3;\n    }\n    cfg = &gfc->cfg;\n    esv = &gfc->sv_enc;\n    \n    /* Was flush already called? */\n    if (esv->mf_samples_to_encode < 1) {\n        return 0;\n    }\n    pcm_samples_per_frame = 576 * cfg->mode_gr;\n    mf_needed = calcNeeded(cfg);\n\n    samples_to_encode = esv->mf_samples_to_encode - POSTDELAY;\n\n    memset(buffer, 0, sizeof(buffer));\n    mp3count = 0;\n\n    is_resampling_necessary = isResamplingNecessary(cfg);\n    if (is_resampling_necessary) {\n        resample_ratio = (double)cfg->samplerate_in / (double)cfg->samplerate_out;\n        /* delay due to resampling; needs to be fixed, if resampling code gets changed */\n        samples_to_encode += 16. / resample_ratio;\n    }\n    end_padding = pcm_samples_per_frame - (samples_to_encode % pcm_samples_per_frame);\n    if (end_padding < 576)\n        end_padding += pcm_samples_per_frame;\n    gfc->ov_enc.encoder_padding = end_padding;\n    \n    frames_left = (samples_to_encode + end_padding) / pcm_samples_per_frame;\n    while (frames_left > 0 && imp3 >= 0) {\n        int const frame_num = gfc->ov_enc.frame_number;\n        int     bunch = mf_needed - esv->mf_size;\n\n        bunch *= resample_ratio;\n        if (bunch > 1152) bunch = 1152;\n        if (bunch < 1) bunch = 1;\n\n        mp3buffer_size_remaining = mp3buffer_size - mp3count;\n\n        /* if user specifed buffer size = 0, dont check size */\n        if (mp3buffer_size == 0)\n            mp3buffer_size_remaining = 0;\n\n        /* send in a frame of 0 padding until all internal sample buffers\n         * are flushed\n         */\n        imp3 = lame_encode_buffer(gfp, buffer[0], buffer[1], bunch,\n                                  mp3buffer, mp3buffer_size_remaining);\n\n        mp3buffer += imp3;\n        mp3count += imp3;\n        frames_left -= ((frame_num != gfc->ov_enc.frame_number) ? 1 : 0);\n    }\n    /* Set esv->mf_samples_to_encode to 0, so we may detect\n     * and break loops calling it more than once in a row.\n     */\n    esv->mf_samples_to_encode = 0;\n\n    if (imp3 < 0) {\n        /* some type of fatal error */\n        return imp3;\n    }\n\n    mp3buffer_size_remaining = mp3buffer_size - mp3count;\n    /* if user specifed buffer size = 0, dont check size */\n    if (mp3buffer_size == 0)\n        mp3buffer_size_remaining = 0;\n\n    /* mp3 related stuff.  bit buffer might still contain some mp3 data */\n    flush_bitstream(gfc);\n    imp3 = copy_buffer(gfc, mp3buffer, mp3buffer_size_remaining, 1);\n    save_gain_values(gfc);\n    if (imp3 < 0) {\n        /* some type of fatal error */\n        return imp3;\n    }\n    mp3buffer += imp3;\n    mp3count += imp3;\n    mp3buffer_size_remaining = mp3buffer_size - mp3count;\n    /* if user specifed buffer size = 0, dont check size */\n    if (mp3buffer_size == 0)\n        mp3buffer_size_remaining = 0;\n\n    if (gfp->write_id3tag_automatic) {\n        /* write a id3 tag to the bitstream */\n        (void) id3tag_write_v1(gfp);\n\n        imp3 = copy_buffer(gfc, mp3buffer, mp3buffer_size_remaining, 0);\n\n        if (imp3 < 0) {\n            return imp3;\n        }\n        mp3count += imp3;\n    }\n#if 0\n    {\n        int const ed = gfc->ov_enc.encoder_delay;\n        int const ep = gfc->ov_enc.encoder_padding;\n        int const ns = (gfc->ov_enc.frame_number * pcm_samples_per_frame) - (ed + ep);\n        double  duration = ns;\n        duration /= cfg->samplerate_out;\n        MSGF(gfc, \"frames=%d\\n\", gfc->ov_enc.frame_number);\n        MSGF(gfc, \"pcm_samples_per_frame=%d\\n\", pcm_samples_per_frame);\n        MSGF(gfc, \"encoder delay=%d\\n\", ed);\n        MSGF(gfc, \"encoder padding=%d\\n\", ep);\n        MSGF(gfc, \"sample count=%d (%g)\\n\", ns, cfg->samplerate_in * duration);\n        MSGF(gfc, \"duration=%g sec\\n\", duration);\n    }\n#endif\n    return mp3count;\n}\n\n/***********************************************************************\n *\n *      lame_close ()\n *\n *  frees internal buffers\n *\n ***********************************************************************/\n\nint\nlame_close(lame_global_flags * gfp)\n{\n    int     ret = 0;\n    if (gfp && gfp->class_id == LAME_ID) {\n        lame_internal_flags *const gfc = gfp->internal_flags;\n        gfp->class_id = 0;\n        if (NULL == gfc || gfc->class_id != LAME_ID) {\n            ret = -3;\n        }\n        if (NULL != gfc) {\n            gfc->class_id = 0;\n            /* this routine will free all malloc'd data in gfc, and then free gfc: */\n            freegfc(gfc);\n            gfp->internal_flags = NULL;\n        }\n        if (gfp->lame_allocated_gfp) {\n            gfp->lame_allocated_gfp = 0;\n            free(gfp);\n        }\n    }\n    return ret;\n}\n\n/*****************************************************************/\n/* flush internal mp3 buffers, and free internal buffers         */\n/*****************************************************************/\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\nint CDECL\nlame_encode_finish(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size);\n#else\n#endif\n\nint\nlame_encode_finish(lame_global_flags * gfp, unsigned char *mp3buffer, int mp3buffer_size)\n{\n    int const ret = lame_encode_flush(gfp, mp3buffer, mp3buffer_size);\n\n    (void) lame_close(gfp);\n\n    return ret;\n}\n\n/*****************************************************************/\n/* write VBR Xing header, and ID3 version 1 tag, if asked for    */\n/*****************************************************************/\nvoid    lame_mp3_tags_fid(lame_global_flags * gfp, FILE * fpStream);\n\nvoid\nlame_mp3_tags_fid(lame_global_flags * gfp, FILE * fpStream)\n{\n    lame_internal_flags *gfc;\n    SessionConfig_t const *cfg;\n    if (!is_lame_global_flags_valid(gfp)) {\n        return;\n    }\n    gfc = gfp->internal_flags;\n    if (!is_lame_internal_flags_valid(gfc)) {\n        return;\n    }\n    cfg = &gfc->cfg;\n    if (!cfg->write_lame_tag) {\n        return;\n    }\n    /* Write Xing header again */\n    if (fpStream && !fseek(fpStream, 0, SEEK_SET)) {\n        int     rc = PutVbrTag(gfp, fpStream);\n        switch (rc) {\n        default:\n            /* OK */\n            break;\n\n        case -1:\n            ERRORF(gfc, \"Error: could not update LAME tag.\\n\");\n            break;\n\n        case -2:\n            ERRORF(gfc, \"Error: could not update LAME tag, file not seekable.\\n\");\n            break;\n\n        case -3:\n            ERRORF(gfc, \"Error: could not update LAME tag, file not readable.\\n\");\n            break;\n        }\n    }\n}\n\n\n\n/* initialize mp3 encoder */\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\nstatic\n#else\n#endif\nint\nlame_init_old(lame_global_flags * gfp)\n{\n    lame_internal_flags *gfc;\n    SessionConfig_t *cfg;\n\n    disable_FPE();      /* disable floating point exceptions */\n\n    memset(gfp, 0, sizeof(lame_global_flags));\n\n    gfp->class_id = LAME_ID;\n\n    if (NULL == (gfc = gfp->internal_flags = calloc(1, sizeof(lame_internal_flags))))\n        return -1;\n\n    cfg = &gfc->cfg;\n\n    /* Global flags.  set defaults here for non-zero values */\n    /* see lame.h for description */\n    /* set integer values to -1 to mean that LAME will compute the\n     * best value, UNLESS the calling program as set it\n     * (and the value is no longer -1)\n     */\n    gfp->strict_ISO = MDB_MAXIMUM;\n\n    gfp->mode = NOT_SET;\n    gfp->original = 1;\n    gfp->samplerate_in = 44100;\n    gfp->num_channels = 2;\n    gfp->num_samples = MAX_U_32_NUM;\n\n    gfp->write_lame_tag = 1;\n    gfp->quality = -1;\n    gfp->short_blocks = short_block_not_set;\n    gfp->subblock_gain = -1;\n\n    gfp->lowpassfreq = 0;\n    gfp->highpassfreq = 0;\n    gfp->lowpasswidth = -1;\n    gfp->highpasswidth = -1;\n\n    gfp->VBR = vbr_off;\n    gfp->VBR_q = 4;\n    gfp->ATHcurve = -1;\n    gfp->VBR_mean_bitrate_kbps = 128;\n    gfp->VBR_min_bitrate_kbps = 0;\n    gfp->VBR_max_bitrate_kbps = 0;\n    gfp->VBR_hard_min = 0;\n    cfg->vbr_min_bitrate_index = 1; /* not  0 ????? */\n    cfg->vbr_max_bitrate_index = 13; /* not 14 ????? */\n\n    gfp->quant_comp = -1;\n    gfp->quant_comp_short = -1;\n\n    gfp->msfix = -1;\n\n    gfc->sv_qnt.OldValue[0] = 180;\n    gfc->sv_qnt.OldValue[1] = 180;\n    gfc->sv_qnt.CurrentStep[0] = 4;\n    gfc->sv_qnt.CurrentStep[1] = 4;\n    gfc->sv_qnt.masking_lower = 1;\n\n    gfp->attackthre = -1;\n    gfp->attackthre_s = -1;\n\n    gfp->scale = 1;\n    gfp->scale_left = 1;\n    gfp->scale_right = 1;\n\n    gfp->athaa_type = -1;\n    gfp->ATHtype = -1;  /* default = -1 = set in lame_init_params */\n    /* 2 = equal loudness curve */\n    gfp->athaa_sensitivity = 0.0; /* no offset */\n    gfp->useTemporal = -1;\n    gfp->interChRatio = -1;\n\n    /* The reason for\n     *       int mf_samples_to_encode = ENCDELAY + POSTDELAY;\n     * ENCDELAY = internal encoder delay.  And then we have to add POSTDELAY=288\n     * because of the 50% MDCT overlap.  A 576 MDCT granule decodes to\n     * 1152 samples.  To synthesize the 576 samples centered under this granule\n     * we need the previous granule for the first 288 samples (no problem), and\n     * the next granule for the next 288 samples (not possible if this is last\n     * granule).  So we need to pad with 288 samples to make sure we can\n     * encode the 576 samples we are interested in.\n     */\n    gfc->sv_enc.mf_samples_to_encode = ENCDELAY + POSTDELAY;\n    gfc->ov_enc.encoder_padding = 0;\n    gfc->sv_enc.mf_size = ENCDELAY - MDCTDELAY; /* we pad input with this many 0's */\n\n    gfp->findReplayGain = 0;\n    gfp->decode_on_the_fly = 0;\n\n    gfc->cfg.decode_on_the_fly = 0;\n    gfc->cfg.findReplayGain = 0;\n    gfc->cfg.findPeakSample = 0;\n\n    gfc->ov_rpg.RadioGain = 0;\n    gfc->ov_rpg.noclipGainChange = 0;\n    gfc->ov_rpg.noclipScale = -1.0;\n\n    gfp->asm_optimizations.mmx = 1;\n    gfp->asm_optimizations.amd3dnow = 1;\n    gfp->asm_optimizations.sse = 1;\n\n    gfp->preset = 0;\n\n    gfp->write_id3tag_automatic = 1;\n\n    gfp->report.debugf = &lame_report_def;\n    gfp->report.errorf = &lame_report_def;\n    gfp->report.msgf = &lame_report_def;\n    return 0;\n}\n\n\n\nlame_global_flags *\nlame_init(void)\n{\n    lame_global_flags *gfp;\n    int     ret;\n\n    init_log_table();\n\n    gfp = calloc(1, sizeof(lame_global_flags));\n    if (gfp == NULL)\n        return NULL;\n\n    ret = lame_init_old(gfp);\n    if (ret != 0) {\n        free(gfp);\n        return NULL;\n    }\n\n    gfp->lame_allocated_gfp = 1;\n    return gfp;\n}\n\n/***********************************************************************\n *\n *  some simple statistics\n *\n *  Robert Hegemann 2000-10-11\n *\n ***********************************************************************/\n\n/*  histogram of used bitrate indexes:\n *  One has to weight them to calculate the average bitrate in kbps\n *\n *  bitrate indices:\n *  there are 14 possible bitrate indices, 0 has the special meaning\n *  \"free format\" which is not possible to mix with VBR and 15 is forbidden\n *  anyway.\n *\n *  stereo modes:\n *  0: LR   number of left-right encoded frames\n *  1: LR-I number of left-right and intensity encoded frames\n *  2: MS   number of mid-side encoded frames\n *  3: MS-I number of mid-side and intensity encoded frames\n *\n *  4: number of encoded frames\n *\n */\n\nvoid\nlame_bitrate_kbps(const lame_global_flags * gfp, int bitrate_kbps[14])\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            SessionConfig_t const *const cfg = &gfc->cfg;\n            int     i;\n            if (cfg->free_format) {\n                for (i = 0; i < 14; i++)\n                    bitrate_kbps[i] = -1;\n                bitrate_kbps[0] = cfg->avg_bitrate;\n            }\n            else {\n                for (i = 0; i < 14; i++)\n                    bitrate_kbps[i] = bitrate_table[cfg->version][i + 1];\n            }\n        }\n    }\n}\n\n\nvoid\nlame_bitrate_hist(const lame_global_flags * gfp, int bitrate_count[14])\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            SessionConfig_t const *const cfg = &gfc->cfg;\n            EncResult_t const *const eov = &gfc->ov_enc;\n            int     i;\n\n            if (cfg->free_format) {\n                for (i = 0; i < 14; i++) {\n                    bitrate_count[i] = 0;\n                }\n                bitrate_count[0] = eov->bitrate_channelmode_hist[0][4];\n            }\n            else {\n                for (i = 0; i < 14; i++) {\n                    bitrate_count[i] = eov->bitrate_channelmode_hist[i + 1][4];\n                }\n            }\n        }\n    }\n}\n\n\nvoid\nlame_stereo_mode_hist(const lame_global_flags * gfp, int stmode_count[4])\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            EncResult_t const *const eov = &gfc->ov_enc;\n            int     i;\n\n            for (i = 0; i < 4; i++) {\n                stmode_count[i] = eov->bitrate_channelmode_hist[15][i];\n            }\n        }\n    }\n}\n\n\n\nvoid\nlame_bitrate_stereo_mode_hist(const lame_global_flags * gfp, int bitrate_stmode_count[14][4])\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            SessionConfig_t const *const cfg = &gfc->cfg;\n            EncResult_t const *const eov = &gfc->ov_enc;\n            int     i;\n            int     j;\n\n            if (cfg->free_format) {\n                for (j = 0; j < 14; j++)\n                    for (i = 0; i < 4; i++) {\n                        bitrate_stmode_count[j][i] = 0;\n                    }\n                for (i = 0; i < 4; i++) {\n                    bitrate_stmode_count[0][i] = eov->bitrate_channelmode_hist[0][i];\n                }\n            }\n            else {\n                for (j = 0; j < 14; j++) {\n                    for (i = 0; i < 4; i++) {\n                        bitrate_stmode_count[j][i] = eov->bitrate_channelmode_hist[j + 1][i];\n                    }\n                }\n            }\n        }\n    }\n}\n\n\nvoid\nlame_block_type_hist(const lame_global_flags * gfp, int btype_count[6])\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            EncResult_t const *const eov = &gfc->ov_enc;\n            int     i;\n\n            for (i = 0; i < 6; ++i) {\n                btype_count[i] = eov->bitrate_blocktype_hist[15][i];\n            }\n        }\n    }\n}\n\n\n\nvoid\nlame_bitrate_block_type_hist(const lame_global_flags * gfp, int bitrate_btype_count[14][6])\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            SessionConfig_t const *const cfg = &gfc->cfg;\n            EncResult_t const *const eov = &gfc->ov_enc;\n            int     i, j;\n\n            if (cfg->free_format) {\n                for (j = 0; j < 14; ++j) {\n                    for (i = 0; i < 6; ++i) {\n                        bitrate_btype_count[j][i] = 0;\n                    }\n                }\n                for (i = 0; i < 6; ++i) {\n                    bitrate_btype_count[0][i] = eov->bitrate_blocktype_hist[0][i];\n                }\n            }\n            else {\n                for (j = 0; j < 14; ++j) {\n                    for (i = 0; i < 6; ++i) {\n                        bitrate_btype_count[j][i] = eov->bitrate_blocktype_hist[j + 1][i];\n                    }\n                }\n            }\n        }\n    }\n}\n\n/* end of lame.c */\n"
  },
  {
    "path": "app/jni/libmp3lame/lame_global_flags.h",
    "content": "#ifndef LAME_GLOBAL_FLAGS_H\n#define LAME_GLOBAL_FLAGS_H\n\n#ifndef lame_internal_flags_defined\n#define lame_internal_flags_defined\nstruct lame_internal_flags;\ntypedef struct lame_internal_flags lame_internal_flags;\n#endif\n\n\ntypedef enum short_block_e {\n    short_block_not_set = -1, /* allow LAME to decide */\n    short_block_allowed = 0, /* LAME may use them, even different block types for L/R */\n    short_block_coupled, /* LAME may use them, but always same block types in L/R */\n    short_block_dispensed, /* LAME will not use short blocks, long blocks only */\n    short_block_forced  /* LAME will not use long blocks, short blocks only */\n} short_block_t;\n\n/***********************************************************************\n*\n*  Control Parameters set by User.  These parameters are here for\n*  backwards compatibility with the old, non-shared lib API.\n*  Please use the lame_set_variablename() functions below\n*\n*\n***********************************************************************/\nstruct lame_global_struct {\n    unsigned int class_id;\n\n    /* input description */\n    unsigned long num_samples; /* number of samples. default=2^32-1           */\n    int     num_channels;    /* input number of channels. default=2         */\n    int     samplerate_in;   /* input_samp_rate in Hz. default=44.1 kHz     */\n    int     samplerate_out;  /* output_samp_rate.\n                                default: LAME picks best value\n                                at least not used for MP3 decoding:\n                                Remember 44.1 kHz MP3s and AC97           */\n    float   scale;           /* scale input by this amount before encoding\n                                at least not used for MP3 decoding          */\n    float   scale_left;      /* scale input of channel 0 (left) by this\n                                amount before encoding                      */\n    float   scale_right;     /* scale input of channel 1 (right) by this\n                                amount before encoding                      */\n\n    /* general control params */\n    int     analysis;        /* collect data for a MP3 frame analyzer?      */\n    int     write_lame_tag;  /* add Xing VBR tag?                           */\n    int     decode_only;     /* use lame/mpglib to convert mp3 to wav       */\n    int     quality;         /* quality setting 0=best,  9=worst  default=5 */\n    MPEG_mode mode;          /* see enum in lame.h\n                                default = LAME picks best value             */\n    int     force_ms;        /* force M/S mode.  requires mode=1            */\n    int     free_format;     /* use free format? default=0                  */\n    int     findReplayGain;  /* find the RG value? default=0       */\n    int     decode_on_the_fly; /* decode on the fly? default=0                */\n    int     write_id3tag_automatic; /* 1 (default) writes ID3 tags, 0 not */\n\n    int     nogap_total;\n    int     nogap_current;\n\n    int     substep_shaping;\n    int     noise_shaping;\n    int     subblock_gain;   /*  0 = no, 1 = yes */\n    int     use_best_huffman; /* 0 = no.  1=outside loop  2=inside loop(slow) */\n\n    /*\n     * set either brate>0  or compression_ratio>0, LAME will compute\n     * the value of the variable not set.\n     * Default is compression_ratio = 11.025\n     */\n    int     brate;           /* bitrate                                    */\n    float   compression_ratio; /* sizeof(wav file)/sizeof(mp3 file)          */\n\n\n    /* frame params */\n    int     copyright;       /* mark as copyright. default=0           */\n    int     original;        /* mark as original. default=1            */\n    int     extension;       /* the MP3 'private extension' bit.\n                                Meaningless                            */\n    int     emphasis;        /* Input PCM is emphased PCM (for\n                                instance from one of the rarely\n                                emphased CDs), it is STRONGLY not\n                                recommended to use this, because\n                                psycho does not take it into account,\n                                and last but not least many decoders\n                                don't care about these bits          */\n    int     error_protection; /* use 2 bytes per frame for a CRC\n                                 checksum. default=0                    */\n    int     strict_ISO;      /* enforce ISO spec as much as possible   */\n\n    int     disable_reservoir; /* use bit reservoir?                     */\n\n    /* quantization/noise shaping */\n    int     quant_comp;\n    int     quant_comp_short;\n    int     experimentalY;\n    int     experimentalZ;\n    int     exp_nspsytune;\n\n    int     preset;\n\n    /* VBR control */\n    vbr_mode VBR;\n    float   VBR_q_frac;      /* Range [0,...,1[ */\n    int     VBR_q;           /* Range [0,...,9] */\n    int     VBR_mean_bitrate_kbps;\n    int     VBR_min_bitrate_kbps;\n    int     VBR_max_bitrate_kbps;\n    int     VBR_hard_min;    /* strictly enforce VBR_min_bitrate\n                                normaly, it will be violated for analog\n                                silence                                 */\n\n\n    /* resampling and filtering */\n    int     lowpassfreq;     /* freq in Hz. 0=lame choses.\n                                -1=no filter                          */\n    int     highpassfreq;    /* freq in Hz. 0=lame choses.\n                                -1=no filter                          */\n    int     lowpasswidth;    /* freq width of filter, in Hz\n                                (default=15%)                         */\n    int     highpasswidth;   /* freq width of filter, in Hz\n                                (default=15%)                         */\n\n\n\n    /*\n     * psycho acoustics and other arguments which you should not change\n     * unless you know what you are doing\n     */\n    float   maskingadjust;\n    float   maskingadjust_short;\n    int     ATHonly;         /* only use ATH                         */\n    int     ATHshort;        /* only use ATH for short blocks        */\n    int     noATH;           /* disable ATH                          */\n    int     ATHtype;         /* select ATH formula                   */\n    float   ATHcurve;        /* change ATH formula 4 shape           */\n    float   ATH_lower_db;    /* lower ATH by this many db            */\n    int     athaa_type;      /* select ATH auto-adjust scheme        */\n    float   athaa_sensitivity; /* dB, tune active region of auto-level */\n    short_block_t short_blocks;\n    int     useTemporal;     /* use temporal masking effect          */\n    float   interChRatio;\n    float   msfix;           /* Naoki's adjustment of Mid/Side maskings */\n\n    int     tune;            /* 0 off, 1 on */\n    float   tune_value_a;    /* used to pass values for debugging and stuff */\n\n    float   attackthre;      /* attack threshold for L/R/M channel */\n    float   attackthre_s;    /* attack threshold for S channel */\n\n\n    struct {\n        void    (*msgf) (const char *format, va_list ap);\n        void    (*debugf) (const char *format, va_list ap);\n        void    (*errorf) (const char *format, va_list ap);\n    } report;\n\n  /************************************************************************/\n    /* internal variables, do not set...                                    */\n    /* provided because they may be of use to calling application           */\n  /************************************************************************/\n\n    int     lame_allocated_gfp; /* is this struct owned by calling\n                                   program or lame?                     */\n\n\n\n  /**************************************************************************/\n    /* more internal variables are stored in this structure:                  */\n  /**************************************************************************/\n    lame_internal_flags *internal_flags;\n\n\n    struct {\n        int     mmx;\n        int     amd3dnow;\n        int     sse;\n\n    } asm_optimizations;\n};\n\nint     is_lame_global_flags_valid(const lame_global_flags * gfp);\n\n#endif /* LAME_GLOBAL_FLAGS_H */\n"
  },
  {
    "path": "app/jni/libmp3lame/lameerror.h",
    "content": "/*\n *  A collection of LAME Error Codes\n *\n *  Please use the constants defined here instead of some arbitrary\n *  values. Currently the values starting at -10 to avoid intersection\n *  with the -1, -2, -3 and -4 used in the current code.\n *\n *  May be this should be a part of the include/lame.h.\n */\n\ntypedef enum {\n    LAME_OKAY = 0,\n    LAME_NOERROR = 0,\n    LAME_GENERICERROR = -1,\n    LAME_NOMEM = -10,\n    LAME_BADBITRATE = -11,\n    LAME_BADSAMPFREQ = -12,\n    LAME_INTERNALERROR = -13,\n\n    FRONTEND_READERROR = -80,\n    FRONTEND_WRITEERROR = -81,\n    FRONTEND_FILETOOLARGE = -82,\n\n} lame_errorcodes_t;\n\n/* end of lameerror.h */\n"
  },
  {
    "path": "app/jni/libmp3lame/machine.h",
    "content": "/*\n *      Machine dependent defines/includes for LAME.\n *\n *      Copyright (c) 1999 A.L. Faber\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_MACHINE_H\n#define LAME_MACHINE_H\n\n#include \"version.h\"\n\n#if (LAME_RELEASE_VERSION == 0)\n#undef NDEBUG\n#endif\n#include <strings.h>\n#include <stdio.h>\n#include <assert.h>\n\n#ifdef STDC_HEADERS\n# include <stdlib.h>\n# include <string.h>\n#else\n# ifndef HAVE_STRCHR\n#  define strchr index\n#  define strrchr rindex\n# endif\nchar   *strchr(), *strrchr();\n# ifndef HAVE_MEMCPY\n#  define memcpy(d, s, n) bcopy ((s), (d), (n))\n#  define memmove(d, s, n) bcopy ((s), (d), (n))\n# endif\n\n#endif\n\n#if  defined(__riscos__)  &&  defined(FPA10)\n# include \"ymath.h\"\n#else\n# include <math.h>\n#endif\n#include <limits.h>\n\n#include <ctype.h>\n\n#ifdef HAVE_ERRNO_H\n# include <errno.h>\n#endif\n#ifdef HAVE_FCNTL_H\n# include <fcntl.h>\n#endif\n\n#if defined(macintosh)\n# include <types.h>\n# include <stat.h>\n#else\n# include <sys/types.h>\n# include <sys/stat.h>\n#endif\n\n#ifdef HAVE_INTTYPES_H\n# include <inttypes.h>\n#else\n# ifdef HAVE_STDINT_H\n#  include <stdint.h>\n# endif\n#endif\n\n#ifdef WITH_DMALLOC\n#include <dmalloc.h>\n#endif\n\n/*\n * 3 different types of pow() functions:\n *   - table lookup\n *   - pow()\n *   - exp()   on some machines this is claimed to be faster than pow()\n */\n\n#define POW20(x) (assert(0 <= (x+Q_MAX2) && x < Q_MAX), pow20[x+Q_MAX2])\n/*#define POW20(x)  pow(2.0,((double)(x)-210)*.25) */\n/*#define POW20(x)  exp( ((double)(x)-210)*(.25*LOG2) ) */\n\n#define IPOW20(x)  (assert(0 <= x && x < Q_MAX), ipow20[x])\n/*#define IPOW20(x)  exp( -((double)(x)-210)*.1875*LOG2 ) */\n/*#define IPOW20(x)  pow(2.0,-((double)(x)-210)*.1875) */\n\n/* in case this is used without configure */\n#ifndef inline\n# define inline\n#endif\n\n#if defined(_MSC_VER)\n# undef inline\n# define inline _inline\n#elif defined(__SASC) || defined(__GNUC__) || defined(__ICC) || defined(__ECC)\n/* if __GNUC__ we always want to inline, not only if the user requests it */\n# undef inline\n# define inline __inline\n#endif\n\n#if    defined(_MSC_VER)\n# pragma warning( disable : 4244 )\n/*# pragma warning( disable : 4305 ) */\n#endif\n\n/*\n * FLOAT    for variables which require at least 32 bits\n * FLOAT8   for variables which require at least 64 bits\n *\n * On some machines, 64 bit will be faster than 32 bit.  Also, some math\n * routines require 64 bit float, so setting FLOAT=float will result in a\n * lot of conversions.\n */\n\n#if ( defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__) )\n# define WIN32_LEAN_AND_MEAN\n# include <windows.h>\n# include <float.h>\n# define FLOAT_MAX FLT_MAX\n#else\n# ifndef FLOAT\ntypedef float FLOAT;\n#  ifdef FLT_MAX\n#   define FLOAT_MAX FLT_MAX\n#  else\n#   define FLOAT_MAX 1e37 /* approx */\n#  endif\n# endif\n#endif\n\n#ifndef FLOAT8\ntypedef double FLOAT8;\n# ifdef DBL_MAX\n#  define FLOAT8_MAX DBL_MAX\n# else\n#  define FLOAT8_MAX 1e99 /* approx */\n# endif\n#else\n# ifdef FLT_MAX\n#  define FLOAT8_MAX FLT_MAX\n# else\n#  define FLOAT8_MAX 1e37 /* approx */\n# endif\n#endif\n\n/* sample_t must be floating point, at least 32 bits */\ntypedef FLOAT sample_t;\n\n#define dimension_of(array) (sizeof(array)/sizeof(array[0]))\n#define beyond(array) (array+dimension_of(array))\n#define compiletime_assert(expression) extern char static_assert_##FILE##_##LINE[expression?1:0]\n\n#if 1\n#define EQ(a,b) (\\\n(fabs(a) > fabs((float)b)) \\\n ? (fabs((float)((a)-(b))) <= (fabs((float)a) * 1e-6f)) \\\n : (fabs((float)((a)-(b))) <= (fabs((float)b) * 1e-6f)))\n\n#else\n#define EQ(a,b) (fabs((a)-(b))<1E-37)\n#endif\n\n#define NEQ(a,b) (!EQ(a,b))\n\n#endif\n\n#ifdef _MSC_VER\n#  if _MSC_VER < 1400\n#  define fabsf fabs\n#  define powf pow\n#  define log10f log10\n#  endif\n#endif\n\n\n/* end of machine.h */\n"
  },
  {
    "path": "app/jni/libmp3lame/mpglib_interface.c",
    "content": "/* -*- mode: C; mode: fold -*- */\n/*\n *      LAME MP3 encoding engine\n *\n *      Copyright (c) 1999-2000 Mark Taylor\n *      Copyright (c) 2003 Olcios\n *      Copyright (c) 2008 Robert Hegemann\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: mpglib_interface.c,v 1.42 2011/05/07 16:05:17 rbrito Exp $ */\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#ifdef HAVE_MPGLIB\n#define hip_global_struct mpstr_tag \n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"interface.h\"\n\n#include \"util.h\"\n\n\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n/*\n * OBSOLETE:\n * - kept to let it link\n * - forward declaration to silence compiler\n */\nint CDECL lame_decode_init(void);\nint CDECL lame_decode(\n        unsigned char *  mp3buf,\n        int              len,\n        short            pcm_l[],\n        short            pcm_r[] );\nint CDECL lame_decode_headers(\n        unsigned char*   mp3buf,\n        int              len,\n        short            pcm_l[],\n        short            pcm_r[],\n        mp3data_struct*  mp3data );\nint CDECL lame_decode1(\n        unsigned char*  mp3buf,\n        int             len,\n        short           pcm_l[],\n        short           pcm_r[] );\nint CDECL lame_decode1_headers(\n        unsigned char*   mp3buf,\n        int              len,\n        short            pcm_l[],\n        short            pcm_r[],\n        mp3data_struct*  mp3data );\nint CDECL lame_decode1_headersB(\n        unsigned char*   mp3buf,\n        int              len,\n        short            pcm_l[],\n        short            pcm_r[],\n        mp3data_struct*  mp3data,\n        int              *enc_delay,\n        int              *enc_padding );\nint CDECL lame_decode_exit(void);\n#endif\n\n\nstatic MPSTR   mp;\n\nint\nlame_decode_exit(void)\n{\n    ExitMP3(&mp);\n    return 0;\n}\n\n\nint\nlame_decode_init(void)\n{\n    (void) InitMP3(&mp);\n    return 0;\n}\n\n\n\n\n/* copy mono samples */\n#define COPY_MONO(DST_TYPE, SRC_TYPE)                                                           \\\n    DST_TYPE *pcm_l = (DST_TYPE *)pcm_l_raw;                                                    \\\n    SRC_TYPE const *p_samples = (SRC_TYPE const *)p;                                            \\\n    for (i = 0; i < processed_samples; i++)                                                     \\\n      *pcm_l++ = (DST_TYPE)(*p_samples++);\n\n/* copy stereo samples */\n#define COPY_STEREO(DST_TYPE, SRC_TYPE)                                                         \\\n    DST_TYPE *pcm_l = (DST_TYPE *)pcm_l_raw, *pcm_r = (DST_TYPE *)pcm_r_raw;                    \\\n    SRC_TYPE const *p_samples = (SRC_TYPE const *)p;                                            \\\n    for (i = 0; i < processed_samples; i++) {                                                   \\\n      *pcm_l++ = (DST_TYPE)(*p_samples++);                                                      \\\n      *pcm_r++ = (DST_TYPE)(*p_samples++);                                                      \\\n    }\n\n\n\n/*\n * For lame_decode:  return code\n * -1     error\n *  0     ok, but need more data before outputing any samples\n *  n     number of samples output.  either 576 or 1152 depending on MP3 file.\n */\n\nstatic int\ndecode1_headersB_clipchoice(PMPSTR pmp, unsigned char *buffer, int len,\n                            char pcm_l_raw[], char pcm_r_raw[], mp3data_struct * mp3data,\n                            int *enc_delay, int *enc_padding,\n                            char *p, size_t psize, int decoded_sample_size,\n                            int (*decodeMP3_ptr) (PMPSTR, unsigned char *, int, char *, int,\n                            int *))\n{\n    static const int smpls[2][4] = {\n        /* Layer   I    II   III */\n        {0, 384, 1152, 1152}, /* MPEG-1     */\n        {0, 384, 1152, 576} /* MPEG-2(.5) */\n    };\n\n    int     processed_bytes;\n    int     processed_samples; /* processed samples per channel */\n    int     ret;\n    int     i;\n\n    mp3data->header_parsed = 0;\n\n    ret = (*decodeMP3_ptr) (pmp, buffer, len, p, (int) psize, &processed_bytes);\n    /* three cases:  \n     * 1. headers parsed, but data not complete\n     *       pmp->header_parsed==1 \n     *       pmp->framesize=0           \n     *       pmp->fsizeold=size of last frame, or 0 if this is first frame\n     *\n     * 2. headers, data parsed, but ancillary data not complete\n     *       pmp->header_parsed==1 \n     *       pmp->framesize=size of frame           \n     *       pmp->fsizeold=size of last frame, or 0 if this is first frame\n     *\n     * 3. frame fully decoded:  \n     *       pmp->header_parsed==0 \n     *       pmp->framesize=0           \n     *       pmp->fsizeold=size of frame (which is now the last frame)\n     *\n     */\n    if (pmp->header_parsed || pmp->fsizeold > 0 || pmp->framesize > 0) {\n        mp3data->header_parsed = 1;\n        mp3data->stereo = pmp->fr.stereo;\n        mp3data->samplerate = freqs[pmp->fr.sampling_frequency];\n        mp3data->mode = pmp->fr.mode;\n        mp3data->mode_ext = pmp->fr.mode_ext;\n        mp3data->framesize = smpls[pmp->fr.lsf][pmp->fr.lay];\n\n        /* free format, we need the entire frame before we can determine\n         * the bitrate.  If we haven't gotten the entire frame, bitrate=0 */\n        if (pmp->fsizeold > 0) /* works for free format and fixed, no overrun, temporal results are < 400.e6 */\n            mp3data->bitrate = 8 * (4 + pmp->fsizeold) * mp3data->samplerate /\n                (1.e3 * mp3data->framesize) + 0.5;\n        else if (pmp->framesize > 0)\n            mp3data->bitrate = 8 * (4 + pmp->framesize) * mp3data->samplerate /\n                (1.e3 * mp3data->framesize) + 0.5;\n        else\n            mp3data->bitrate = tabsel_123[pmp->fr.lsf][pmp->fr.lay - 1][pmp->fr.bitrate_index];\n\n\n\n        if (pmp->num_frames > 0) {\n            /* Xing VBR header found and num_frames was set */\n            mp3data->totalframes = pmp->num_frames;\n            mp3data->nsamp = mp3data->framesize * pmp->num_frames;\n            *enc_delay = pmp->enc_delay;\n            *enc_padding = pmp->enc_padding;\n        }\n    }\n\n    switch (ret) {\n    case MP3_OK:\n        switch (pmp->fr.stereo) {\n        case 1:\n            processed_samples = processed_bytes / decoded_sample_size;\n            if (decoded_sample_size == sizeof(short)) {\n                COPY_MONO(short, short)\n            }\n            else {\n                COPY_MONO(sample_t, FLOAT)\n            }\n            break;\n        case 2:\n            processed_samples = (processed_bytes / decoded_sample_size) >> 1;\n            if (decoded_sample_size == sizeof(short)) {\n                COPY_STEREO(short, short)\n            }\n            else {\n                COPY_STEREO(sample_t, FLOAT)\n            }\n            break;\n        default:\n            processed_samples = -1;\n            assert(0);\n            break;\n        }\n        break;\n\n    case MP3_NEED_MORE:\n        processed_samples = 0;\n        break;\n\n    case MP3_ERR:\n        processed_samples = -1;\n        break;\n\n    default:\n        processed_samples = -1;\n        assert(0);\n        break;\n    }\n\n    /*fprintf(stderr,\"ok, more, err:  %i %i %i\\n\", MP3_OK, MP3_NEED_MORE, MP3_ERR ); */\n    /*fprintf(stderr,\"ret = %i out=%i\\n\", ret, processed_samples ); */\n    return processed_samples;\n}\n\n\n#define OUTSIZE_CLIPPED   (4096*sizeof(short))\n\nint\nlame_decode1_headersB(unsigned char *buffer,\n                      int len,\n                      short pcm_l[], short pcm_r[], mp3data_struct * mp3data,\n                      int *enc_delay, int *enc_padding)\n{\n    static char out[OUTSIZE_CLIPPED];\n\n    return decode1_headersB_clipchoice(&mp, buffer, len, (char *) pcm_l, (char *) pcm_r, mp3data,\n                                       enc_delay, enc_padding, out, OUTSIZE_CLIPPED,\n                                       sizeof(short), decodeMP3);\n}\n\n\n\n\n\n/*\n * For lame_decode:  return code\n *  -1     error\n *   0     ok, but need more data before outputing any samples\n *   n     number of samples output.  Will be at most one frame of\n *         MPEG data.  \n */\n\nint\nlame_decode1_headers(unsigned char *buffer,\n                     int len, short pcm_l[], short pcm_r[], mp3data_struct * mp3data)\n{\n    int     enc_delay, enc_padding;\n    return lame_decode1_headersB(buffer, len, pcm_l, pcm_r, mp3data, &enc_delay, &enc_padding);\n}\n\n\nint\nlame_decode1(unsigned char *buffer, int len, short pcm_l[], short pcm_r[])\n{\n    mp3data_struct mp3data;\n\n    return lame_decode1_headers(buffer, len, pcm_l, pcm_r, &mp3data);\n}\n\n\n/*\n * For lame_decode:  return code\n *  -1     error\n *   0     ok, but need more data before outputing any samples\n *   n     number of samples output.  a multiple of 576 or 1152 depending on MP3 file.\n */\n\nint\nlame_decode_headers(unsigned char *buffer,\n                    int len, short pcm_l[], short pcm_r[], mp3data_struct * mp3data)\n{\n    int     ret;\n    int     totsize = 0;     /* number of decoded samples per channel */\n\n    for (;;) {\n        switch (ret = lame_decode1_headers(buffer, len, pcm_l + totsize, pcm_r + totsize, mp3data)) {\n        case -1:\n            return ret;\n        case 0:\n            return totsize;\n        default:\n            totsize += ret;\n            len = 0;    /* future calls to decodeMP3 are just to flush buffers */\n            break;\n        }\n    }\n}\n\n\nint\nlame_decode(unsigned char *buffer, int len, short pcm_l[], short pcm_r[])\n{\n    mp3data_struct mp3data;\n\n    return lame_decode_headers(buffer, len, pcm_l, pcm_r, &mp3data);\n}\n\n\n\n\nhip_t hip_decode_init(void)\n{\n    hip_t hip = calloc(1, sizeof(hip_global_flags));\n    InitMP3(hip);\n    return hip;\n}\n\n\nint hip_decode_exit(hip_t hip)\n{\n    if (hip) {\n        ExitMP3(hip);\n        free(hip);\n    }\n    return 0;\n}\n\n\n/* we forbid input with more than 1152 samples per channel for output in the unclipped mode */\n#define OUTSIZE_UNCLIPPED (1152*2*sizeof(FLOAT))\n\nint\nhip_decode1_unclipped(hip_t hip, unsigned char *buffer, size_t len, sample_t pcm_l[], sample_t pcm_r[])\n{\n    static char out[OUTSIZE_UNCLIPPED];\n    mp3data_struct mp3data;\n    int     enc_delay, enc_padding;\n\n    if (hip) {\n        return decode1_headersB_clipchoice(hip, buffer, len, (char *) pcm_l, (char *) pcm_r, &mp3data,\n                                           &enc_delay, &enc_padding, out, OUTSIZE_UNCLIPPED,\n                                           sizeof(FLOAT), decodeMP3_unclipped);\n    }\n    return 0;\n}\n\n/*\n * For hip_decode:  return code\n *  -1     error\n *   0     ok, but need more data before outputing any samples\n *   n     number of samples output.  Will be at most one frame of\n *         MPEG data.  \n */\n\nint\nhip_decode1_headers(hip_t hip, unsigned char *buffer,\n                     size_t len, short pcm_l[], short pcm_r[], mp3data_struct * mp3data)\n{\n    int     enc_delay, enc_padding;\n    return hip_decode1_headersB(hip, buffer, len, pcm_l, pcm_r, mp3data, &enc_delay, &enc_padding);\n}\n\n\nint\nhip_decode1(hip_t hip, unsigned char *buffer, size_t len, short pcm_l[], short pcm_r[])\n{\n    mp3data_struct mp3data;\n    return hip_decode1_headers(hip, buffer, len, pcm_l, pcm_r, &mp3data);\n}\n\n\n/*\n * For hip_decode:  return code\n *  -1     error\n *   0     ok, but need more data before outputing any samples\n *   n     number of samples output.  a multiple of 576 or 1152 depending on MP3 file.\n */\n\nint\nhip_decode_headers(hip_t hip, unsigned char *buffer,\n                    size_t len, short pcm_l[], short pcm_r[], mp3data_struct * mp3data)\n{\n    int     ret;\n    int     totsize = 0;     /* number of decoded samples per channel */\n\n    for (;;) {\n        switch (ret = hip_decode1_headers(hip, buffer, len, pcm_l + totsize, pcm_r + totsize, mp3data)) {\n        case -1:\n            return ret;\n        case 0:\n            return totsize;\n        default:\n            totsize += ret;\n            len = 0;    /* future calls to decodeMP3 are just to flush buffers */\n            break;\n        }\n    }\n}\n\n\nint\nhip_decode(hip_t hip, unsigned char *buffer, size_t len, short pcm_l[], short pcm_r[])\n{\n    mp3data_struct mp3data;\n    return hip_decode_headers(hip, buffer, len, pcm_l, pcm_r, &mp3data);\n}\n\n\nint\nhip_decode1_headersB(hip_t hip, unsigned char *buffer,\n                      size_t len,\n                      short pcm_l[], short pcm_r[], mp3data_struct * mp3data,\n                      int *enc_delay, int *enc_padding)\n{\n    static char out[OUTSIZE_CLIPPED];\n    if (hip) {\n        return decode1_headersB_clipchoice(hip, buffer, len, (char *) pcm_l, (char *) pcm_r, mp3data,\n                                           enc_delay, enc_padding, out, OUTSIZE_CLIPPED,\n                                           sizeof(short), decodeMP3);\n    }\n    return -1;\n}\n\n\nvoid hip_set_pinfo(hip_t hip, plotting_data* pinfo)\n{\n    if (hip) {\n        hip->pinfo = pinfo;\n    }\n}\n\n\n\nvoid hip_set_errorf(hip_t hip, lame_report_function func)\n{\n    if (hip) {\n        hip->report_err = func;\n    }\n}\n\nvoid hip_set_debugf(hip_t hip, lame_report_function func)\n{\n    if (hip) {\n        hip->report_dbg = func;\n    }\n}\n\nvoid hip_set_msgf  (hip_t hip, lame_report_function func)\n{\n    if (hip) {\n        hip->report_msg = func;\n    }\n}\n\n#endif\n\n/* end of mpglib_interface.c */\n"
  },
  {
    "path": "app/jni/libmp3lame/newmdct.c",
    "content": "/*\n *      MP3 window subband -> subband filtering -> mdct routine\n *\n *      Copyright (c) 1999-2000 Takehiro Tominaga\n *\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/*\n *         Special Thanks to Patrick De Smet for your advices.\n */\n\n/* $Id: newmdct.c,v 1.39 2011/05/07 16:05:17 rbrito Exp $ */\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include <string.h>\n#include <strings.h>\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"newmdct.h\"\n\n\n\n#ifndef USE_GOGO_SUBBAND\nstatic const FLOAT enwindow[] = {\n    -4.77e-07 * 0.740951125354959 / 2.384e-06, 1.03951e-04 * 0.740951125354959 / 2.384e-06,\n    9.53674e-04 * 0.740951125354959 / 2.384e-06, 2.841473e-03 * 0.740951125354959 / 2.384e-06,\n    3.5758972e-02 * 0.740951125354959 / 2.384e-06, 3.401756e-03 * 0.740951125354959 / 2.384e-06, 9.83715e-04 * 0.740951125354959 / 2.384e-06, 9.9182e-05 * 0.740951125354959 / 2.384e-06, /* 15 */\n    1.2398e-05 * 0.740951125354959 / 2.384e-06, 1.91212e-04 * 0.740951125354959 / 2.384e-06,\n    2.283096e-03 * 0.740951125354959 / 2.384e-06, 1.6994476e-02 * 0.740951125354959 / 2.384e-06,\n    -1.8756866e-02 * 0.740951125354959 / 2.384e-06, -2.630711e-03 * 0.740951125354959 / 2.384e-06,\n    -2.47478e-04 * 0.740951125354959 / 2.384e-06, -1.4782e-05 * 0.740951125354959 / 2.384e-06,\n    9.063471690191471e-01,\n    1.960342806591213e-01,\n\n\n    -4.77e-07 * 0.773010453362737 / 2.384e-06, 1.05858e-04 * 0.773010453362737 / 2.384e-06,\n    9.30786e-04 * 0.773010453362737 / 2.384e-06, 2.521515e-03 * 0.773010453362737 / 2.384e-06,\n    3.5694122e-02 * 0.773010453362737 / 2.384e-06, 3.643036e-03 * 0.773010453362737 / 2.384e-06, 9.91821e-04 * 0.773010453362737 / 2.384e-06, 9.6321e-05 * 0.773010453362737 / 2.384e-06, /* 14 */\n    1.1444e-05 * 0.773010453362737 / 2.384e-06, 1.65462e-04 * 0.773010453362737 / 2.384e-06,\n    2.110004e-03 * 0.773010453362737 / 2.384e-06, 1.6112804e-02 * 0.773010453362737 / 2.384e-06,\n    -1.9634247e-02 * 0.773010453362737 / 2.384e-06, -2.803326e-03 * 0.773010453362737 / 2.384e-06,\n    -2.77042e-04 * 0.773010453362737 / 2.384e-06, -1.6689e-05 * 0.773010453362737 / 2.384e-06,\n    8.206787908286602e-01,\n    3.901806440322567e-01,\n\n\n    -4.77e-07 * 0.803207531480645 / 2.384e-06, 1.07288e-04 * 0.803207531480645 / 2.384e-06,\n    9.02653e-04 * 0.803207531480645 / 2.384e-06, 2.174854e-03 * 0.803207531480645 / 2.384e-06,\n    3.5586357e-02 * 0.803207531480645 / 2.384e-06, 3.858566e-03 * 0.803207531480645 / 2.384e-06, 9.95159e-04 * 0.803207531480645 / 2.384e-06, 9.3460e-05 * 0.803207531480645 / 2.384e-06, /* 13 */\n    1.0014e-05 * 0.803207531480645 / 2.384e-06, 1.40190e-04 * 0.803207531480645 / 2.384e-06,\n    1.937389e-03 * 0.803207531480645 / 2.384e-06, 1.5233517e-02 * 0.803207531480645 / 2.384e-06,\n    -2.0506859e-02 * 0.803207531480645 / 2.384e-06, -2.974033e-03 * 0.803207531480645 / 2.384e-06,\n    -3.07560e-04 * 0.803207531480645 / 2.384e-06, -1.8120e-05 * 0.803207531480645 / 2.384e-06,\n    7.416505462720353e-01,\n    5.805693545089249e-01,\n\n\n    -4.77e-07 * 0.831469612302545 / 2.384e-06, 1.08242e-04 * 0.831469612302545 / 2.384e-06,\n    8.68797e-04 * 0.831469612302545 / 2.384e-06, 1.800537e-03 * 0.831469612302545 / 2.384e-06,\n    3.5435200e-02 * 0.831469612302545 / 2.384e-06, 4.049301e-03 * 0.831469612302545 / 2.384e-06, 9.94205e-04 * 0.831469612302545 / 2.384e-06, 9.0599e-05 * 0.831469612302545 / 2.384e-06, /* 12 */\n    9.060e-06 * 0.831469612302545 / 2.384e-06, 1.16348e-04 * 0.831469612302545 / 2.384e-06,\n    1.766682e-03 * 0.831469612302545 / 2.384e-06, 1.4358521e-02 * 0.831469612302545 / 2.384e-06,\n    -2.1372318e-02 * 0.831469612302545 / 2.384e-06, -3.14188e-03 * 0.831469612302545 / 2.384e-06,\n    -3.39031e-04 * 0.831469612302545 / 2.384e-06, -1.9550e-05 * 0.831469612302545 / 2.384e-06,\n    6.681786379192989e-01,\n    7.653668647301797e-01,\n\n\n    -4.77e-07 * 0.857728610000272 / 2.384e-06, 1.08719e-04 * 0.857728610000272 / 2.384e-06,\n    8.29220e-04 * 0.857728610000272 / 2.384e-06, 1.399517e-03 * 0.857728610000272 / 2.384e-06,\n    3.5242081e-02 * 0.857728610000272 / 2.384e-06, 4.215240e-03 * 0.857728610000272 / 2.384e-06, 9.89437e-04 * 0.857728610000272 / 2.384e-06, 8.7261e-05 * 0.857728610000272 / 2.384e-06, /* 11 */\n    8.106e-06 * 0.857728610000272 / 2.384e-06, 9.3937e-05 * 0.857728610000272 / 2.384e-06,\n    1.597881e-03 * 0.857728610000272 / 2.384e-06, 1.3489246e-02 * 0.857728610000272 / 2.384e-06,\n    -2.2228718e-02 * 0.857728610000272 / 2.384e-06, -3.306866e-03 * 0.857728610000272 / 2.384e-06,\n    -3.71456e-04 * 0.857728610000272 / 2.384e-06, -2.1458e-05 * 0.857728610000272 / 2.384e-06,\n    5.993769336819237e-01,\n    9.427934736519954e-01,\n\n\n    -4.77e-07 * 0.881921264348355 / 2.384e-06, 1.08719e-04 * 0.881921264348355 / 2.384e-06,\n    7.8392e-04 * 0.881921264348355 / 2.384e-06, 9.71317e-04 * 0.881921264348355 / 2.384e-06,\n    3.5007000e-02 * 0.881921264348355 / 2.384e-06, 4.357815e-03 * 0.881921264348355 / 2.384e-06, 9.80854e-04 * 0.881921264348355 / 2.384e-06, 8.3923e-05 * 0.881921264348355 / 2.384e-06, /* 10 */\n    7.629e-06 * 0.881921264348355 / 2.384e-06, 7.2956e-05 * 0.881921264348355 / 2.384e-06,\n    1.432419e-03 * 0.881921264348355 / 2.384e-06, 1.2627602e-02 * 0.881921264348355 / 2.384e-06,\n    -2.3074150e-02 * 0.881921264348355 / 2.384e-06, -3.467083e-03 * 0.881921264348355 / 2.384e-06,\n    -4.04358e-04 * 0.881921264348355 / 2.384e-06, -2.3365e-05 * 0.881921264348355 / 2.384e-06,\n    5.345111359507916e-01,\n    1.111140466039205e+00,\n\n\n    -9.54e-07 * 0.903989293123443 / 2.384e-06, 1.08242e-04 * 0.903989293123443 / 2.384e-06,\n    7.31945e-04 * 0.903989293123443 / 2.384e-06, 5.15938e-04 * 0.903989293123443 / 2.384e-06,\n    3.4730434e-02 * 0.903989293123443 / 2.384e-06, 4.477024e-03 * 0.903989293123443 / 2.384e-06, 9.68933e-04 * 0.903989293123443 / 2.384e-06, 8.0585e-05 * 0.903989293123443 / 2.384e-06, /* 9 */\n    6.676e-06 * 0.903989293123443 / 2.384e-06, 5.2929e-05 * 0.903989293123443 / 2.384e-06,\n    1.269817e-03 * 0.903989293123443 / 2.384e-06, 1.1775017e-02 * 0.903989293123443 / 2.384e-06,\n    -2.3907185e-02 * 0.903989293123443 / 2.384e-06, -3.622532e-03 * 0.903989293123443 / 2.384e-06,\n    -4.38213e-04 * 0.903989293123443 / 2.384e-06, -2.5272e-05 * 0.903989293123443 / 2.384e-06,\n    4.729647758913199e-01,\n    1.268786568327291e+00,\n\n\n    -9.54e-07 * 0.92387953251128675613 / 2.384e-06,\n    1.06812e-04 * 0.92387953251128675613 / 2.384e-06,\n    6.74248e-04 * 0.92387953251128675613 / 2.384e-06,\n    3.3379e-05 * 0.92387953251128675613 / 2.384e-06,\n    3.4412861e-02 * 0.92387953251128675613 / 2.384e-06,\n    4.573822e-03 * 0.92387953251128675613 / 2.384e-06,\n    9.54151e-04 * 0.92387953251128675613 / 2.384e-06,\n    7.6771e-05 * 0.92387953251128675613 / 2.384e-06,\n    6.199e-06 * 0.92387953251128675613 / 2.384e-06, 3.4332e-05 * 0.92387953251128675613 / 2.384e-06,\n    1.111031e-03 * 0.92387953251128675613 / 2.384e-06,\n    1.0933399e-02 * 0.92387953251128675613 / 2.384e-06,\n    -2.4725437e-02 * 0.92387953251128675613 / 2.384e-06,\n    -3.771782e-03 * 0.92387953251128675613 / 2.384e-06,\n    -4.72546e-04 * 0.92387953251128675613 / 2.384e-06,\n    -2.7657e-05 * 0.92387953251128675613 / 2.384e-06,\n    4.1421356237309504879e-01, /* tan(PI/8) */\n    1.414213562373095e+00,\n\n\n    -9.54e-07 * 0.941544065183021 / 2.384e-06, 1.05381e-04 * 0.941544065183021 / 2.384e-06,\n    6.10352e-04 * 0.941544065183021 / 2.384e-06, -4.75883e-04 * 0.941544065183021 / 2.384e-06,\n    3.4055710e-02 * 0.941544065183021 / 2.384e-06, 4.649162e-03 * 0.941544065183021 / 2.384e-06, 9.35555e-04 * 0.941544065183021 / 2.384e-06, 7.3433e-05 * 0.941544065183021 / 2.384e-06, /* 7 */\n    5.245e-06 * 0.941544065183021 / 2.384e-06, 1.7166e-05 * 0.941544065183021 / 2.384e-06,\n    9.56535e-04 * 0.941544065183021 / 2.384e-06, 1.0103703e-02 * 0.941544065183021 / 2.384e-06,\n    -2.5527000e-02 * 0.941544065183021 / 2.384e-06, -3.914356e-03 * 0.941544065183021 / 2.384e-06,\n    -5.07355e-04 * 0.941544065183021 / 2.384e-06, -3.0041e-05 * 0.941544065183021 / 2.384e-06,\n    3.578057213145241e-01,\n    1.546020906725474e+00,\n\n\n    -9.54e-07 * 0.956940335732209 / 2.384e-06, 1.02520e-04 * 0.956940335732209 / 2.384e-06,\n    5.39303e-04 * 0.956940335732209 / 2.384e-06, -1.011848e-03 * 0.956940335732209 / 2.384e-06,\n    3.3659935e-02 * 0.956940335732209 / 2.384e-06, 4.703045e-03 * 0.956940335732209 / 2.384e-06, 9.15051e-04 * 0.956940335732209 / 2.384e-06, 7.0095e-05 * 0.956940335732209 / 2.384e-06, /* 6 */\n    4.768e-06 * 0.956940335732209 / 2.384e-06, 9.54e-07 * 0.956940335732209 / 2.384e-06,\n    8.06808e-04 * 0.956940335732209 / 2.384e-06, 9.287834e-03 * 0.956940335732209 / 2.384e-06,\n    -2.6310921e-02 * 0.956940335732209 / 2.384e-06, -4.048824e-03 * 0.956940335732209 / 2.384e-06,\n    -5.42164e-04 * 0.956940335732209 / 2.384e-06, -3.2425e-05 * 0.956940335732209 / 2.384e-06,\n    3.033466836073424e-01,\n    1.662939224605090e+00,\n\n\n    -1.431e-06 * 0.970031253194544 / 2.384e-06, 9.9182e-05 * 0.970031253194544 / 2.384e-06,\n    4.62532e-04 * 0.970031253194544 / 2.384e-06, -1.573563e-03 * 0.970031253194544 / 2.384e-06,\n    3.3225536e-02 * 0.970031253194544 / 2.384e-06, 4.737377e-03 * 0.970031253194544 / 2.384e-06, 8.91685e-04 * 0.970031253194544 / 2.384e-06, 6.6280e-05 * 0.970031253194544 / 2.384e-06, /* 5 */\n    4.292e-06 * 0.970031253194544 / 2.384e-06, -1.3828e-05 * 0.970031253194544 / 2.384e-06,\n    6.61850e-04 * 0.970031253194544 / 2.384e-06, 8.487225e-03 * 0.970031253194544 / 2.384e-06,\n    -2.7073860e-02 * 0.970031253194544 / 2.384e-06, -4.174709e-03 * 0.970031253194544 / 2.384e-06,\n    -5.76973e-04 * 0.970031253194544 / 2.384e-06, -3.4809e-05 * 0.970031253194544 / 2.384e-06,\n    2.504869601913055e-01,\n    1.763842528696710e+00,\n\n\n    -1.431e-06 * 0.98078528040323 / 2.384e-06, 9.5367e-05 * 0.98078528040323 / 2.384e-06,\n    3.78609e-04 * 0.98078528040323 / 2.384e-06, -2.161503e-03 * 0.98078528040323 / 2.384e-06,\n    3.2754898e-02 * 0.98078528040323 / 2.384e-06, 4.752159e-03 * 0.98078528040323 / 2.384e-06, 8.66413e-04 * 0.98078528040323 / 2.384e-06, 6.2943e-05 * 0.98078528040323 / 2.384e-06, /* 4 */\n    3.815e-06 * 0.98078528040323 / 2.384e-06, -2.718e-05 * 0.98078528040323 / 2.384e-06,\n    5.22137e-04 * 0.98078528040323 / 2.384e-06, 7.703304e-03 * 0.98078528040323 / 2.384e-06,\n    -2.7815342e-02 * 0.98078528040323 / 2.384e-06, -4.290581e-03 * 0.98078528040323 / 2.384e-06,\n    -6.11782e-04 * 0.98078528040323 / 2.384e-06, -3.7670e-05 * 0.98078528040323 / 2.384e-06,\n    1.989123673796580e-01,\n    1.847759065022573e+00,\n\n\n    -1.907e-06 * 0.989176509964781 / 2.384e-06, 9.0122e-05 * 0.989176509964781 / 2.384e-06,\n    2.88486e-04 * 0.989176509964781 / 2.384e-06, -2.774239e-03 * 0.989176509964781 / 2.384e-06,\n    3.2248020e-02 * 0.989176509964781 / 2.384e-06, 4.748821e-03 * 0.989176509964781 / 2.384e-06, 8.38757e-04 * 0.989176509964781 / 2.384e-06, 5.9605e-05 * 0.989176509964781 / 2.384e-06, /* 3 */\n    3.338e-06 * 0.989176509964781 / 2.384e-06, -3.9577e-05 * 0.989176509964781 / 2.384e-06,\n    3.88145e-04 * 0.989176509964781 / 2.384e-06, 6.937027e-03 * 0.989176509964781 / 2.384e-06,\n    -2.8532982e-02 * 0.989176509964781 / 2.384e-06, -4.395962e-03 * 0.989176509964781 / 2.384e-06,\n    -6.46591e-04 * 0.989176509964781 / 2.384e-06, -4.0531e-05 * 0.989176509964781 / 2.384e-06,\n    1.483359875383474e-01,\n    1.913880671464418e+00,\n\n\n    -1.907e-06 * 0.995184726672197 / 2.384e-06, 8.4400e-05 * 0.995184726672197 / 2.384e-06,\n    1.91689e-04 * 0.995184726672197 / 2.384e-06, -3.411293e-03 * 0.995184726672197 / 2.384e-06,\n    3.1706810e-02 * 0.995184726672197 / 2.384e-06, 4.728317e-03 * 0.995184726672197 / 2.384e-06,\n    8.09669e-04 * 0.995184726672197 / 2.384e-06, 5.579e-05 * 0.995184726672197 / 2.384e-06,\n    3.338e-06 * 0.995184726672197 / 2.384e-06, -5.0545e-05 * 0.995184726672197 / 2.384e-06,\n    2.59876e-04 * 0.995184726672197 / 2.384e-06, 6.189346e-03 * 0.995184726672197 / 2.384e-06,\n    -2.9224873e-02 * 0.995184726672197 / 2.384e-06, -4.489899e-03 * 0.995184726672197 / 2.384e-06,\n    -6.80923e-04 * 0.995184726672197 / 2.384e-06, -4.3392e-05 * 0.995184726672197 / 2.384e-06,\n    9.849140335716425e-02,\n    1.961570560806461e+00,\n\n\n    -2.384e-06 * 0.998795456205172 / 2.384e-06, 7.7724e-05 * 0.998795456205172 / 2.384e-06,\n    8.8215e-05 * 0.998795456205172 / 2.384e-06, -4.072189e-03 * 0.998795456205172 / 2.384e-06,\n    3.1132698e-02 * 0.998795456205172 / 2.384e-06, 4.691124e-03 * 0.998795456205172 / 2.384e-06,\n    7.79152e-04 * 0.998795456205172 / 2.384e-06, 5.2929e-05 * 0.998795456205172 / 2.384e-06,\n    2.861e-06 * 0.998795456205172 / 2.384e-06, -6.0558e-05 * 0.998795456205172 / 2.384e-06,\n    1.37329e-04 * 0.998795456205172 / 2.384e-06, 5.462170e-03 * 0.998795456205172 / 2.384e-06,\n    -2.9890060e-02 * 0.998795456205172 / 2.384e-06, -4.570484e-03 * 0.998795456205172 / 2.384e-06,\n    -7.14302e-04 * 0.998795456205172 / 2.384e-06, -4.6253e-05 * 0.998795456205172 / 2.384e-06,\n    4.912684976946725e-02,\n    1.990369453344394e+00,\n\n\n    3.5780907e-02 * SQRT2 * 0.5 / 2.384e-06, 1.7876148e-02 * SQRT2 * 0.5 / 2.384e-06,\n    3.134727e-03 * SQRT2 * 0.5 / 2.384e-06, 2.457142e-03 * SQRT2 * 0.5 / 2.384e-06,\n    9.71317e-04 * SQRT2 * 0.5 / 2.384e-06, 2.18868e-04 * SQRT2 * 0.5 / 2.384e-06,\n    1.01566e-04 * SQRT2 * 0.5 / 2.384e-06, 1.3828e-05 * SQRT2 * 0.5 / 2.384e-06,\n\n    3.0526638e-02 / 2.384e-06, 4.638195e-03 / 2.384e-06, 7.47204e-04 / 2.384e-06,\n    4.9591e-05 / 2.384e-06,\n    4.756451e-03 / 2.384e-06, 2.1458e-05 / 2.384e-06, -6.9618e-05 / 2.384e-06, /*    2.384e-06/2.384e-06 */\n};\n#endif\n\n\n#define NS 12\n#define NL 36\n\nstatic const FLOAT win[4][NL] = {\n    {\n     2.382191739347913e-13,\n     6.423305872147834e-13,\n     9.400849094049688e-13,\n     1.122435026096556e-12,\n     1.183840321267481e-12,\n     1.122435026096556e-12,\n     9.400849094049690e-13,\n     6.423305872147839e-13,\n     2.382191739347918e-13,\n\n     5.456116108943412e-12,\n     4.878985199565852e-12,\n     4.240448995017367e-12,\n     3.559909094758252e-12,\n     2.858043359288075e-12,\n     2.156177623817898e-12,\n     1.475637723558783e-12,\n     8.371015190102974e-13,\n     2.599706096327376e-13,\n\n     -5.456116108943412e-12,\n     -4.878985199565852e-12,\n     -4.240448995017367e-12,\n     -3.559909094758252e-12,\n     -2.858043359288076e-12,\n     -2.156177623817898e-12,\n     -1.475637723558783e-12,\n     -8.371015190102975e-13,\n     -2.599706096327376e-13,\n\n     -2.382191739347923e-13,\n     -6.423305872147843e-13,\n     -9.400849094049696e-13,\n     -1.122435026096556e-12,\n     -1.183840321267481e-12,\n     -1.122435026096556e-12,\n     -9.400849094049694e-13,\n     -6.423305872147840e-13,\n     -2.382191739347918e-13,\n     },\n    {\n     2.382191739347913e-13,\n     6.423305872147834e-13,\n     9.400849094049688e-13,\n     1.122435026096556e-12,\n     1.183840321267481e-12,\n     1.122435026096556e-12,\n     9.400849094049688e-13,\n     6.423305872147841e-13,\n     2.382191739347918e-13,\n\n     5.456116108943413e-12,\n     4.878985199565852e-12,\n     4.240448995017367e-12,\n     3.559909094758253e-12,\n     2.858043359288075e-12,\n     2.156177623817898e-12,\n     1.475637723558782e-12,\n     8.371015190102975e-13,\n     2.599706096327376e-13,\n\n     -5.461314069809755e-12,\n     -4.921085770524055e-12,\n     -4.343405037091838e-12,\n     -3.732668368707687e-12,\n     -3.093523840190885e-12,\n     -2.430835727329465e-12,\n     -1.734679010007751e-12,\n     -9.748253656609281e-13,\n     -2.797435120168326e-13,\n\n     0.000000000000000e+00,\n     0.000000000000000e+00,\n     0.000000000000000e+00,\n     0.000000000000000e+00,\n     0.000000000000000e+00,\n     0.000000000000000e+00,\n     -2.283748241799531e-13,\n     -4.037858874020686e-13,\n     -2.146547464825323e-13,\n     },\n    {\n     1.316524975873958e-01, /* win[SHORT_TYPE] */\n     4.142135623730950e-01,\n     7.673269879789602e-01,\n\n     1.091308501069271e+00, /* tantab_l */\n     1.303225372841206e+00,\n     1.569685577117490e+00,\n     1.920982126971166e+00,\n     2.414213562373094e+00,\n     3.171594802363212e+00,\n     4.510708503662055e+00,\n     7.595754112725146e+00,\n     2.290376554843115e+01,\n\n     0.98480775301220802032, /* cx */\n     0.64278760968653936292,\n     0.34202014332566882393,\n     0.93969262078590842791,\n     -0.17364817766693030343,\n     -0.76604444311897790243,\n     0.86602540378443870761,\n     0.500000000000000e+00,\n\n     -5.144957554275265e-01, /* ca */\n     -4.717319685649723e-01,\n     -3.133774542039019e-01,\n     -1.819131996109812e-01,\n     -9.457419252642064e-02,\n     -4.096558288530405e-02,\n     -1.419856857247115e-02,\n     -3.699974673760037e-03,\n\n     8.574929257125442e-01, /* cs */\n     8.817419973177052e-01,\n     9.496286491027329e-01,\n     9.833145924917901e-01,\n     9.955178160675857e-01,\n     9.991605581781475e-01,\n     9.998991952444470e-01,\n     9.999931550702802e-01,\n     },\n    {\n     0.000000000000000e+00,\n     0.000000000000000e+00,\n     0.000000000000000e+00,\n     0.000000000000000e+00,\n     0.000000000000000e+00,\n     0.000000000000000e+00,\n     2.283748241799531e-13,\n     4.037858874020686e-13,\n     2.146547464825323e-13,\n\n     5.461314069809755e-12,\n     4.921085770524055e-12,\n     4.343405037091838e-12,\n     3.732668368707687e-12,\n     3.093523840190885e-12,\n     2.430835727329466e-12,\n     1.734679010007751e-12,\n     9.748253656609281e-13,\n     2.797435120168326e-13,\n\n     -5.456116108943413e-12,\n     -4.878985199565852e-12,\n     -4.240448995017367e-12,\n     -3.559909094758253e-12,\n     -2.858043359288075e-12,\n     -2.156177623817898e-12,\n     -1.475637723558782e-12,\n     -8.371015190102975e-13,\n     -2.599706096327376e-13,\n\n     -2.382191739347913e-13,\n     -6.423305872147834e-13,\n     -9.400849094049688e-13,\n     -1.122435026096556e-12,\n     -1.183840321267481e-12,\n     -1.122435026096556e-12,\n     -9.400849094049688e-13,\n     -6.423305872147841e-13,\n     -2.382191739347918e-13,\n     }\n};\n\n#define tantab_l (win[SHORT_TYPE]+3)\n#define cx (win[SHORT_TYPE]+12)\n#define ca (win[SHORT_TYPE]+20)\n#define cs (win[SHORT_TYPE]+28)\n\n/************************************************************************\n*\n* window_subband()\n*\n* PURPOSE:  Overlapping window on PCM samples\n*\n* SEMANTICS:\n* 32 16-bit pcm samples are scaled to fractional 2's complement and\n* concatenated to the end of the window buffer #x#. The updated window\n* buffer #x# is then windowed by the analysis window #c# to produce the\n* windowed sample #z#\n*\n************************************************************************/\n\n/*\n *      new IDCT routine written by Takehiro TOMINAGA\n */\nstatic const int order[] = {\n    0, 1, 16, 17, 8, 9, 24, 25, 4, 5, 20, 21, 12, 13, 28, 29,\n    2, 3, 18, 19, 10, 11, 26, 27, 6, 7, 22, 23, 14, 15, 30, 31\n};\n\n\n/* returns sum_j=0^31 a[j]*cos(PI*j*(k+1/2)/32), 0<=k<32 */\ninline static void\nwindow_subband(const sample_t * x1, FLOAT a[SBLIMIT])\n{\n    int     i;\n    FLOAT const *wp = enwindow + 10;\n\n    const sample_t *x2 = &x1[238 - 14 - 286];\n\n    for (i = -15; i < 0; i++) {\n        FLOAT   w, s, t;\n\n        w = wp[-10];\n        s = x2[-224] * w;\n        t = x1[224] * w;\n        w = wp[-9];\n        s += x2[-160] * w;\n        t += x1[160] * w;\n        w = wp[-8];\n        s += x2[-96] * w;\n        t += x1[96] * w;\n        w = wp[-7];\n        s += x2[-32] * w;\n        t += x1[32] * w;\n        w = wp[-6];\n        s += x2[32] * w;\n        t += x1[-32] * w;\n        w = wp[-5];\n        s += x2[96] * w;\n        t += x1[-96] * w;\n        w = wp[-4];\n        s += x2[160] * w;\n        t += x1[-160] * w;\n        w = wp[-3];\n        s += x2[224] * w;\n        t += x1[-224] * w;\n\n        w = wp[-2];\n        s += x1[-256] * w;\n        t -= x2[256] * w;\n        w = wp[-1];\n        s += x1[-192] * w;\n        t -= x2[192] * w;\n        w = wp[0];\n        s += x1[-128] * w;\n        t -= x2[128] * w;\n        w = wp[1];\n        s += x1[-64] * w;\n        t -= x2[64] * w;\n        w = wp[2];\n        s += x1[0] * w;\n        t -= x2[0] * w;\n        w = wp[3];\n        s += x1[64] * w;\n        t -= x2[-64] * w;\n        w = wp[4];\n        s += x1[128] * w;\n        t -= x2[-128] * w;\n        w = wp[5];\n        s += x1[192] * w;\n        t -= x2[-192] * w;\n\n        /*\n         * this multiplyer could be removed, but it needs more 256 FLOAT data.\n         * thinking about the data cache performance, I think we should not\n         * use such a huge table. tt 2000/Oct/25\n         */\n        s *= wp[6];\n        w = t - s;\n        a[30 + i * 2] = t + s;\n        a[31 + i * 2] = wp[7] * w;\n        wp += 18;\n        x1--;\n        x2++;\n    }\n    {\n        FLOAT   s, t, u, v;\n        t = x1[-16] * wp[-10];\n        s = x1[-32] * wp[-2];\n        t += (x1[-48] - x1[16]) * wp[-9];\n        s += x1[-96] * wp[-1];\n        t += (x1[-80] + x1[48]) * wp[-8];\n        s += x1[-160] * wp[0];\n        t += (x1[-112] - x1[80]) * wp[-7];\n        s += x1[-224] * wp[1];\n        t += (x1[-144] + x1[112]) * wp[-6];\n        s -= x1[32] * wp[2];\n        t += (x1[-176] - x1[144]) * wp[-5];\n        s -= x1[96] * wp[3];\n        t += (x1[-208] + x1[176]) * wp[-4];\n        s -= x1[160] * wp[4];\n        t += (x1[-240] - x1[208]) * wp[-3];\n        s -= x1[224];\n\n        u = s - t;\n        v = s + t;\n\n        t = a[14];\n        s = a[15] - t;\n\n        a[31] = v + t;  /* A0 */\n        a[30] = u + s;  /* A1 */\n        a[15] = u - s;  /* A2 */\n        a[14] = v - t;  /* A3 */\n    }\n    {\n        FLOAT   xr;\n        xr = a[28] - a[0];\n        a[0] += a[28];\n        a[28] = xr * wp[-2 * 18 + 7];\n        xr = a[29] - a[1];\n        a[1] += a[29];\n        a[29] = xr * wp[-2 * 18 + 7];\n\n        xr = a[26] - a[2];\n        a[2] += a[26];\n        a[26] = xr * wp[-4 * 18 + 7];\n        xr = a[27] - a[3];\n        a[3] += a[27];\n        a[27] = xr * wp[-4 * 18 + 7];\n\n        xr = a[24] - a[4];\n        a[4] += a[24];\n        a[24] = xr * wp[-6 * 18 + 7];\n        xr = a[25] - a[5];\n        a[5] += a[25];\n        a[25] = xr * wp[-6 * 18 + 7];\n\n        xr = a[22] - a[6];\n        a[6] += a[22];\n        a[22] = xr * SQRT2;\n        xr = a[23] - a[7];\n        a[7] += a[23];\n        a[23] = xr * SQRT2 - a[7];\n        a[7] -= a[6];\n        a[22] -= a[7];\n        a[23] -= a[22];\n\n        xr = a[6];\n        a[6] = a[31] - xr;\n        a[31] = a[31] + xr;\n        xr = a[7];\n        a[7] = a[30] - xr;\n        a[30] = a[30] + xr;\n        xr = a[22];\n        a[22] = a[15] - xr;\n        a[15] = a[15] + xr;\n        xr = a[23];\n        a[23] = a[14] - xr;\n        a[14] = a[14] + xr;\n\n        xr = a[20] - a[8];\n        a[8] += a[20];\n        a[20] = xr * wp[-10 * 18 + 7];\n        xr = a[21] - a[9];\n        a[9] += a[21];\n        a[21] = xr * wp[-10 * 18 + 7];\n\n        xr = a[18] - a[10];\n        a[10] += a[18];\n        a[18] = xr * wp[-12 * 18 + 7];\n        xr = a[19] - a[11];\n        a[11] += a[19];\n        a[19] = xr * wp[-12 * 18 + 7];\n\n        xr = a[16] - a[12];\n        a[12] += a[16];\n        a[16] = xr * wp[-14 * 18 + 7];\n        xr = a[17] - a[13];\n        a[13] += a[17];\n        a[17] = xr * wp[-14 * 18 + 7];\n\n        xr = -a[20] + a[24];\n        a[20] += a[24];\n        a[24] = xr * wp[-12 * 18 + 7];\n        xr = -a[21] + a[25];\n        a[21] += a[25];\n        a[25] = xr * wp[-12 * 18 + 7];\n\n        xr = a[4] - a[8];\n        a[4] += a[8];\n        a[8] = xr * wp[-12 * 18 + 7];\n        xr = a[5] - a[9];\n        a[5] += a[9];\n        a[9] = xr * wp[-12 * 18 + 7];\n\n        xr = a[0] - a[12];\n        a[0] += a[12];\n        a[12] = xr * wp[-4 * 18 + 7];\n        xr = a[1] - a[13];\n        a[1] += a[13];\n        a[13] = xr * wp[-4 * 18 + 7];\n        xr = a[16] - a[28];\n        a[16] += a[28];\n        a[28] = xr * wp[-4 * 18 + 7];\n        xr = -a[17] + a[29];\n        a[17] += a[29];\n        a[29] = xr * wp[-4 * 18 + 7];\n\n        xr = SQRT2 * (a[2] - a[10]);\n        a[2] += a[10];\n        a[10] = xr;\n        xr = SQRT2 * (a[3] - a[11]);\n        a[3] += a[11];\n        a[11] = xr;\n        xr = SQRT2 * (-a[18] + a[26]);\n        a[18] += a[26];\n        a[26] = xr - a[18];\n        xr = SQRT2 * (-a[19] + a[27]);\n        a[19] += a[27];\n        a[27] = xr - a[19];\n\n        xr = a[2];\n        a[19] -= a[3];\n        a[3] -= xr;\n        a[2] = a[31] - xr;\n        a[31] += xr;\n        xr = a[3];\n        a[11] -= a[19];\n        a[18] -= xr;\n        a[3] = a[30] - xr;\n        a[30] += xr;\n        xr = a[18];\n        a[27] -= a[11];\n        a[19] -= xr;\n        a[18] = a[15] - xr;\n        a[15] += xr;\n\n        xr = a[19];\n        a[10] -= xr;\n        a[19] = a[14] - xr;\n        a[14] += xr;\n        xr = a[10];\n        a[11] -= xr;\n        a[10] = a[23] - xr;\n        a[23] += xr;\n        xr = a[11];\n        a[26] -= xr;\n        a[11] = a[22] - xr;\n        a[22] += xr;\n        xr = a[26];\n        a[27] -= xr;\n        a[26] = a[7] - xr;\n        a[7] += xr;\n\n        xr = a[27];\n        a[27] = a[6] - xr;\n        a[6] += xr;\n\n        xr = SQRT2 * (a[0] - a[4]);\n        a[0] += a[4];\n        a[4] = xr;\n        xr = SQRT2 * (a[1] - a[5]);\n        a[1] += a[5];\n        a[5] = xr;\n        xr = SQRT2 * (a[16] - a[20]);\n        a[16] += a[20];\n        a[20] = xr;\n        xr = SQRT2 * (a[17] - a[21]);\n        a[17] += a[21];\n        a[21] = xr;\n\n        xr = -SQRT2 * (a[8] - a[12]);\n        a[8] += a[12];\n        a[12] = xr - a[8];\n        xr = -SQRT2 * (a[9] - a[13]);\n        a[9] += a[13];\n        a[13] = xr - a[9];\n        xr = -SQRT2 * (a[25] - a[29]);\n        a[25] += a[29];\n        a[29] = xr - a[25];\n        xr = -SQRT2 * (a[24] + a[28]);\n        a[24] -= a[28];\n        a[28] = xr - a[24];\n\n        xr = a[24] - a[16];\n        a[24] = xr;\n        xr = a[20] - xr;\n        a[20] = xr;\n        xr = a[28] - xr;\n        a[28] = xr;\n\n        xr = a[25] - a[17];\n        a[25] = xr;\n        xr = a[21] - xr;\n        a[21] = xr;\n        xr = a[29] - xr;\n        a[29] = xr;\n\n        xr = a[17] - a[1];\n        a[17] = xr;\n        xr = a[9] - xr;\n        a[9] = xr;\n        xr = a[25] - xr;\n        a[25] = xr;\n        xr = a[5] - xr;\n        a[5] = xr;\n        xr = a[21] - xr;\n        a[21] = xr;\n        xr = a[13] - xr;\n        a[13] = xr;\n        xr = a[29] - xr;\n        a[29] = xr;\n\n        xr = a[1] - a[0];\n        a[1] = xr;\n        xr = a[16] - xr;\n        a[16] = xr;\n        xr = a[17] - xr;\n        a[17] = xr;\n        xr = a[8] - xr;\n        a[8] = xr;\n        xr = a[9] - xr;\n        a[9] = xr;\n        xr = a[24] - xr;\n        a[24] = xr;\n        xr = a[25] - xr;\n        a[25] = xr;\n        xr = a[4] - xr;\n        a[4] = xr;\n        xr = a[5] - xr;\n        a[5] = xr;\n        xr = a[20] - xr;\n        a[20] = xr;\n        xr = a[21] - xr;\n        a[21] = xr;\n        xr = a[12] - xr;\n        a[12] = xr;\n        xr = a[13] - xr;\n        a[13] = xr;\n        xr = a[28] - xr;\n        a[28] = xr;\n        xr = a[29] - xr;\n        a[29] = xr;\n\n        xr = a[0];\n        a[0] += a[31];\n        a[31] -= xr;\n        xr = a[1];\n        a[1] += a[30];\n        a[30] -= xr;\n        xr = a[16];\n        a[16] += a[15];\n        a[15] -= xr;\n        xr = a[17];\n        a[17] += a[14];\n        a[14] -= xr;\n        xr = a[8];\n        a[8] += a[23];\n        a[23] -= xr;\n        xr = a[9];\n        a[9] += a[22];\n        a[22] -= xr;\n        xr = a[24];\n        a[24] += a[7];\n        a[7] -= xr;\n        xr = a[25];\n        a[25] += a[6];\n        a[6] -= xr;\n        xr = a[4];\n        a[4] += a[27];\n        a[27] -= xr;\n        xr = a[5];\n        a[5] += a[26];\n        a[26] -= xr;\n        xr = a[20];\n        a[20] += a[11];\n        a[11] -= xr;\n        xr = a[21];\n        a[21] += a[10];\n        a[10] -= xr;\n        xr = a[12];\n        a[12] += a[19];\n        a[19] -= xr;\n        xr = a[13];\n        a[13] += a[18];\n        a[18] -= xr;\n        xr = a[28];\n        a[28] += a[3];\n        a[3] -= xr;\n        xr = a[29];\n        a[29] += a[2];\n        a[2] -= xr;\n    }\n\n}\n\n\n/*-------------------------------------------------------------------*/\n/*                                                                   */\n/*   Function: Calculation of the MDCT                               */\n/*   In the case of long blocks (type 0,1,3) there are               */\n/*   36 coefficents in the time domain and 18 in the frequency       */\n/*   domain.                                                         */\n/*   In the case of short blocks (type 2) there are 3                */\n/*   transformations with short length. This leads to 12 coefficents */\n/*   in the time and 6 in the frequency domain. In this case the     */\n/*   results are stored side by side in the vector out[].            */\n/*                                                                   */\n/*   New layer3                                                      */\n/*                                                                   */\n/*-------------------------------------------------------------------*/\n\ninline static void\nmdct_short(FLOAT * inout)\n{\n    int     l;\n    for (l = 0; l < 3; l++) {\n        FLOAT   tc0, tc1, tc2, ts0, ts1, ts2;\n\n        ts0 = inout[2 * 3] * win[SHORT_TYPE][0] - inout[5 * 3];\n        tc0 = inout[0 * 3] * win[SHORT_TYPE][2] - inout[3 * 3];\n        tc1 = ts0 + tc0;\n        tc2 = ts0 - tc0;\n\n        ts0 = inout[5 * 3] * win[SHORT_TYPE][0] + inout[2 * 3];\n        tc0 = inout[3 * 3] * win[SHORT_TYPE][2] + inout[0 * 3];\n        ts1 = ts0 + tc0;\n        ts2 = -ts0 + tc0;\n\n        tc0 = (inout[1 * 3] * win[SHORT_TYPE][1] - inout[4 * 3]) * 2.069978111953089e-11; /* tritab_s[1] */\n        ts0 = (inout[4 * 3] * win[SHORT_TYPE][1] + inout[1 * 3]) * 2.069978111953089e-11; /* tritab_s[1] */\n\n        inout[3 * 0] = tc1 * 1.907525191737280e-11 /* tritab_s[2] */  + tc0;\n        inout[3 * 5] = -ts1 * 1.907525191737280e-11 /* tritab_s[0] */  + ts0;\n\n        tc2 = tc2 * 0.86602540378443870761 * 1.907525191737281e-11 /* tritab_s[2] */ ;\n        ts1 = ts1 * 0.5 * 1.907525191737281e-11 + ts0;\n        inout[3 * 1] = tc2 - ts1;\n        inout[3 * 2] = tc2 + ts1;\n\n        tc1 = tc1 * 0.5 * 1.907525191737281e-11 - tc0;\n        ts2 = ts2 * 0.86602540378443870761 * 1.907525191737281e-11 /* tritab_s[0] */ ;\n        inout[3 * 3] = tc1 + ts2;\n        inout[3 * 4] = tc1 - ts2;\n\n        inout++;\n    }\n}\n\ninline static void\nmdct_long(FLOAT * out, FLOAT const *in)\n{\n    FLOAT   ct, st;\n    {\n        FLOAT   tc1, tc2, tc3, tc4, ts5, ts6, ts7, ts8;\n        /* 1,2, 5,6, 9,10, 13,14, 17 */\n        tc1 = in[17] - in[9];\n        tc3 = in[15] - in[11];\n        tc4 = in[14] - in[12];\n        ts5 = in[0] + in[8];\n        ts6 = in[1] + in[7];\n        ts7 = in[2] + in[6];\n        ts8 = in[3] + in[5];\n\n        out[17] = (ts5 + ts7 - ts8) - (ts6 - in[4]);\n        st = (ts5 + ts7 - ts8) * cx[7] + (ts6 - in[4]);\n        ct = (tc1 - tc3 - tc4) * cx[6];\n        out[5] = ct + st;\n        out[6] = ct - st;\n\n        tc2 = (in[16] - in[10]) * cx[6];\n        ts6 = ts6 * cx[7] + in[4];\n        ct = tc1 * cx[0] + tc2 + tc3 * cx[1] + tc4 * cx[2];\n        st = -ts5 * cx[4] + ts6 - ts7 * cx[5] + ts8 * cx[3];\n        out[1] = ct + st;\n        out[2] = ct - st;\n\n        ct = tc1 * cx[1] - tc2 - tc3 * cx[2] + tc4 * cx[0];\n        st = -ts5 * cx[5] + ts6 - ts7 * cx[3] + ts8 * cx[4];\n        out[9] = ct + st;\n        out[10] = ct - st;\n\n        ct = tc1 * cx[2] - tc2 + tc3 * cx[0] - tc4 * cx[1];\n        st = ts5 * cx[3] - ts6 + ts7 * cx[4] - ts8 * cx[5];\n        out[13] = ct + st;\n        out[14] = ct - st;\n    }\n    {\n        FLOAT   ts1, ts2, ts3, ts4, tc5, tc6, tc7, tc8;\n\n        ts1 = in[8] - in[0];\n        ts3 = in[6] - in[2];\n        ts4 = in[5] - in[3];\n        tc5 = in[17] + in[9];\n        tc6 = in[16] + in[10];\n        tc7 = in[15] + in[11];\n        tc8 = in[14] + in[12];\n\n        out[0] = (tc5 + tc7 + tc8) + (tc6 + in[13]);\n        ct = (tc5 + tc7 + tc8) * cx[7] - (tc6 + in[13]);\n        st = (ts1 - ts3 + ts4) * cx[6];\n        out[11] = ct + st;\n        out[12] = ct - st;\n\n        ts2 = (in[7] - in[1]) * cx[6];\n        tc6 = in[13] - tc6 * cx[7];\n        ct = tc5 * cx[3] - tc6 + tc7 * cx[4] + tc8 * cx[5];\n        st = ts1 * cx[2] + ts2 + ts3 * cx[0] + ts4 * cx[1];\n        out[3] = ct + st;\n        out[4] = ct - st;\n\n        ct = -tc5 * cx[5] + tc6 - tc7 * cx[3] - tc8 * cx[4];\n        st = ts1 * cx[1] + ts2 - ts3 * cx[2] - ts4 * cx[0];\n        out[7] = ct + st;\n        out[8] = ct - st;\n\n        ct = -tc5 * cx[4] + tc6 - tc7 * cx[5] - tc8 * cx[3];\n        st = ts1 * cx[0] - ts2 + ts3 * cx[1] - ts4 * cx[2];\n        out[15] = ct + st;\n        out[16] = ct - st;\n    }\n}\n\n\nvoid\nmdct_sub48(lame_internal_flags * gfc, const sample_t * w0, const sample_t * w1)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    int     gr, k, ch;\n    const sample_t *wk;\n\n    wk = w0 + 286;\n    /* thinking cache performance, ch->gr loop is better than gr->ch loop */\n    for (ch = 0; ch < cfg->channels_out; ch++) {\n        for (gr = 0; gr < cfg->mode_gr; gr++) {\n            int     band;\n            gr_info *const gi = &(gfc->l3_side.tt[gr][ch]);\n            FLOAT  *mdct_enc = gi->xr;\n            FLOAT  *samp = esv->sb_sample[ch][1 - gr][0];\n\n            for (k = 0; k < 18 / 2; k++) {\n                window_subband(wk, samp);\n                window_subband(wk + 32, samp + 32);\n                samp += 64;\n                wk += 64;\n                /*\n                 * Compensate for inversion in the analysis filter\n                 */\n                for (band = 1; band < 32; band += 2) {\n                    samp[band - 32] *= -1;\n                }\n            }\n\n            /*\n             * Perform imdct of 18 previous subband samples\n             * + 18 current subband samples\n             */\n            for (band = 0; band < 32; band++, mdct_enc += 18) {\n                int     type = gi->block_type;\n                FLOAT const *const band0 = esv->sb_sample[ch][gr][0] + order[band];\n                FLOAT  *const band1 = esv->sb_sample[ch][1 - gr][0] + order[band];\n                if (gi->mixed_block_flag && band < 2)\n                    type = 0;\n                if (esv->amp_filter[band] < 1e-12) {\n                    memset(mdct_enc, 0, 18 * sizeof(FLOAT));\n                }\n                else {\n                    if (esv->amp_filter[band] < 1.0) {\n                        for (k = 0; k < 18; k++)\n                            band1[k * 32] *= esv->amp_filter[band];\n                    }\n                    if (type == SHORT_TYPE) {\n                        for (k = -NS / 4; k < 0; k++) {\n                            FLOAT const w = win[SHORT_TYPE][k + 3];\n                            mdct_enc[k * 3 + 9] = band0[(9 + k) * 32] * w - band0[(8 - k) * 32];\n                            mdct_enc[k * 3 + 18] = band0[(14 - k) * 32] * w + band0[(15 + k) * 32];\n                            mdct_enc[k * 3 + 10] = band0[(15 + k) * 32] * w - band0[(14 - k) * 32];\n                            mdct_enc[k * 3 + 19] = band1[(2 - k) * 32] * w + band1[(3 + k) * 32];\n                            mdct_enc[k * 3 + 11] = band1[(3 + k) * 32] * w - band1[(2 - k) * 32];\n                            mdct_enc[k * 3 + 20] = band1[(8 - k) * 32] * w + band1[(9 + k) * 32];\n                        }\n                        mdct_short(mdct_enc);\n                    }\n                    else {\n                        FLOAT   work[18];\n                        for (k = -NL / 4; k < 0; k++) {\n                            FLOAT   a, b;\n                            a = win[type][k + 27] * band1[(k + 9) * 32]\n                                + win[type][k + 36] * band1[(8 - k) * 32];\n                            b = win[type][k + 9] * band0[(k + 9) * 32]\n                                - win[type][k + 18] * band0[(8 - k) * 32];\n                            work[k + 9] = a - b * tantab_l[k + 9];\n                            work[k + 18] = a * tantab_l[k + 9] + b;\n                        }\n\n                        mdct_long(mdct_enc, work);\n                    }\n                }\n                /*\n                 * Perform aliasing reduction butterfly\n                 */\n                if (type != SHORT_TYPE && band != 0) {\n                    for (k = 7; k >= 0; --k) {\n                        FLOAT   bu, bd;\n                        bu = mdct_enc[k] * ca[k] + mdct_enc[-1 - k] * cs[k];\n                        bd = mdct_enc[k] * cs[k] - mdct_enc[-1 - k] * ca[k];\n\n                        mdct_enc[-1 - k] = bu;\n                        mdct_enc[k] = bd;\n                    }\n                }\n            }\n        }\n        wk = w1 + 286;\n        if (cfg->mode_gr == 1) {\n            memcpy(esv->sb_sample[ch][0], esv->sb_sample[ch][1], 576 * sizeof(FLOAT));\n        }\n    }\n}\n"
  },
  {
    "path": "app/jni/libmp3lame/newmdct.h",
    "content": "/*\n *\tNew Modified DCT include file\n *\n *\tCopyright (c) 1999 Takehiro TOMINAGA\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_NEWMDCT_H\n#define LAME_NEWMDCT_H\n\nvoid    mdct_sub48(lame_internal_flags * gfc, const sample_t * w0, const sample_t * w1);\n\n#endif /* LAME_NEWMDCT_H */\n"
  },
  {
    "path": "app/jni/libmp3lame/presets.c",
    "content": "/*\n * presets.c -- Apply presets\n *\n *\tCopyright (c) 2002-2008 Gabriel Bouvigne\n *\tCopyright (c) 2007-2011 Robert Hegemann\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\n\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"set_get.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"lame_global_flags.h\"\n\n\n#define SET_OPTION(opt, val, def) if (enforce) \\\n    (void) lame_set_##opt(gfp, val); \\\n    else if (!(fabs((float)lame_get_##opt(gfp) - def) > 0)) \\\n    (void) lame_set_##opt(gfp, val);\n\n#define SET__OPTION(opt, val, def) if (enforce) \\\n    lame_set_##opt(gfp, val); \\\n    else if (!(fabs((float)lame_get_##opt(gfp) - def) > 0)) \\\n    lame_set_##opt(gfp, val);\n\n\n\n#undef Min\n#undef Max\n\nstatic inline int\nmin_int(int a, int b)\n{\n    if (a < b) {\n        return a;\n    }\n    return b;\n}\n\nstatic inline int\nmax_int(int a, int b)\n{\n    if (a > b) {\n        return a;\n    }\n    return b;\n}\n\n\n\ntypedef struct {\n    int     vbr_q;\n    int     quant_comp;\n    int     quant_comp_s;\n    int     expY;\n    FLOAT   st_lrm;          /*short threshold */\n    FLOAT   st_s;\n    FLOAT   masking_adj;\n    FLOAT   masking_adj_short;\n    FLOAT   ath_lower;\n    FLOAT   ath_curve;\n    FLOAT   ath_sensitivity;\n    FLOAT   interch;\n    int     safejoint;\n    int     sfb21mod;\n    FLOAT   msfix;\n    FLOAT   minval;\n    FLOAT   ath_fixpoint;\n} vbr_presets_t;\n\n    /* *INDENT-OFF* */\n    \n    /* Switch mappings for VBR mode VBR_RH */\n    static const vbr_presets_t vbr_old_switch_map[] = {\n    /*vbr_q  qcomp_l  qcomp_s  expY  st_lrm   st_s  mask adj_l  adj_s  ath_lower  ath_curve  ath_sens  interChR  safejoint sfb21mod  msfix */\n        {0,       9,       9,    0,   5.20, 125.0,      -4.2,   -6.3,       4.8,       1,          0,   0,              2,      21,  0.97, 5, 100},\n        {1,       9,       9,    0,   5.30, 125.0,      -3.6,   -5.6,       4.5,       1.5,        0,   0,              2,      21,  1.35, 5, 100},\n        {2,       9,       9,    0,   5.60, 125.0,      -2.2,   -3.5,       2.8,       2,          0,   0,              2,      21,  1.49, 5, 100},\n        {3,       9,       9,    1,   5.80, 130.0,      -1.8,   -2.8,       2.6,       3,         -4,   0,              2,      20,  1.64, 5, 100},\n        {4,       9,       9,    1,   6.00, 135.0,      -0.7,   -1.1,       1.1,       3.5,       -8,   0,              2,       0,  1.79, 5, 100},\n        {5,       9,       9,    1,   6.40, 140.0,       0.5,    0.4,      -7.5,       4,        -12,   0.0002,         0,       0,  1.95, 5, 100},\n        {6,       9,       9,    1,   6.60, 145.0,       0.67,   0.65,    -14.7,       6.5,      -19,   0.0004,         0,       0,  2.30, 5, 100},\n        {7,       9,       9,    1,   6.60, 145.0,       0.8,    0.75,    -19.7,       8,        -22,   0.0006,         0,       0,  2.70, 5, 100},\n        {8,       9,       9,    1,   6.60, 145.0,       1.2,    1.15,    -27.5,      10,        -23,   0.0007,         0,       0,  0,    5, 100},\n        {9,       9,       9,    1,   6.60, 145.0,       1.6,    1.6,     -36,        11,        -25,   0.0008,         0,       0,  0,    5, 100},\n        {10,      9,       9,    1,   6.60, 145.0,       2.0,    2.0,     -36,        12,        -25,   0.0008,         0,       0,  0,    5, 100}\n    };\n    \n    static const vbr_presets_t vbr_mt_psy_switch_map[] = {\n    /*vbr_q  qcomp_l  qcomp_s  expY  st_lrm   st_s  mask adj_l  adj_s  ath_lower  ath_curve  ath_sens  ---  safejoint sfb21mod  msfix */\n        {0,       9,       9,    0,   4.20,  25.0,      -6.8,   -6.8,       7.1,       1,          0,   0,         2,      31,  1.000,  5, 100},\n        {1,       9,       9,    0,   4.20,  25.0,      -4.8,   -4.8,       5.4,       1.4,       -1,   0,         2,      27,  1.122,  5,  98},\n        {2,       9,       9,    0,   4.20,  25.0,      -2.6,   -2.6,       3.7,       2.0,       -3,   0,         2,      23,  1.288,  5,  97},\n        {3,       9,       9,    1,   4.20,  25.0,      -1.6,   -1.6,       2.0,       2.0,       -5,   0,         2,      18,  1.479,  5,  96},\n        {4,       9,       9,    1,   4.20,  25.0,      -0.0,   -0.0,       0.0,       2.0,       -8,   0,         2,      12,  1.698,  5,  95},\n        {5,       9,       9,    1,   4.20,  25.0,       1.3,    1.3,      -6,         3.5,      -11,   0,         2,       8,  1.950,  5,  94.2},\n#if 0\n        {6,       9,       9,    1,   4.50, 100.0,       1.5,    1.5,     -24.0,       6.0,      -14,   0,         2,       4,  2.239,  3,  93.9},\n        {7,       9,       9,    1,   4.80, 200.0,       1.7,    1.7,     -28.0,       9.0,      -20,   0,         2,       0,  2.570,  1,  93.6},\n#else\n        {6,       9,       9,    1,   4.50, 100.0,       2.2,    2.3,     -12.0,       6.0,      -14,   0,         2,       4,  2.239,  3,  93.9},\n        {7,       9,       9,    1,   4.80, 200.0,       2.7,    2.7,     -18.0,       9.0,      -17,   0,         2,       0,  2.570,  1,  93.6},\n#endif\n        {8,       9,       9,    1,   5.30, 300.0,       2.8,    2.8,     -21.0,      10.0,      -23,   0.0002,    0,       0,  2.951,  0,  93.3},\n        {9,       9,       9,    1,   6.60, 300.0,       2.8,    2.8,     -23.0,      11.0,      -25,   0.0006,    0,       0,  3.388,  0,  93.3},\n        {10,      9,       9,    1,  25.00, 300.0,       2.8,    2.8,     -25.0,      12.0,      -27,   0.0025,    0,       0,  3.500,  0,  93.3}\n    };\n\n    /* *INDENT-ON* */\n\nstatic vbr_presets_t const*\nget_vbr_preset(int v)\n{\n    switch (v) {\n    case vbr_mtrh:\n    case vbr_mt:\n        return &vbr_mt_psy_switch_map[0];\n    default:\n        return &vbr_old_switch_map[0];\n    }\n}\n\n#define NOOP(m) (void)p.m\n#define LERP(m) (p.m = p.m + x * (q.m - p.m))\n\nstatic void\napply_vbr_preset(lame_global_flags * gfp, int a, int enforce)\n{\n    vbr_presets_t const *vbr_preset = get_vbr_preset(lame_get_VBR(gfp));\n    float   x = gfp->VBR_q_frac;\n    vbr_presets_t p = vbr_preset[a];\n    vbr_presets_t q = vbr_preset[a + 1];\n    vbr_presets_t const *set = &p;\n\n    NOOP(vbr_q);\n    NOOP(quant_comp);\n    NOOP(quant_comp_s);\n    NOOP(expY);\n    LERP(st_lrm);\n    LERP(st_s);\n    LERP(masking_adj);\n    LERP(masking_adj_short);\n    LERP(ath_lower);\n    LERP(ath_curve);\n    LERP(ath_sensitivity);\n    LERP(interch);\n    NOOP(safejoint);\n    LERP(sfb21mod);\n    LERP(msfix);\n    LERP(minval);\n    LERP(ath_fixpoint);\n\n    (void) lame_set_VBR_q(gfp, set->vbr_q);\n    SET_OPTION(quant_comp, set->quant_comp, -1);\n\n//#define SET_OPTION(opt, val, def) if (enforce) \\\n//    (void) lame_set_##opt(gfp, val); \\\n//    else if (!(fabs(lame_get_##opt(gfp) - def) > 0)) \\\n//    (void) lame_set_##opt(gfp, val);\n\n    SET_OPTION(quant_comp_short, set->quant_comp_s, -1);\n    if (set->expY) {\n        (void) lame_set_experimentalY(gfp, set->expY);\n    }\n    SET_OPTION(short_threshold_lrm, set->st_lrm, -1);\n    SET_OPTION(short_threshold_s, set->st_s, -1);\n    SET_OPTION(maskingadjust, set->masking_adj, 0);\n    SET_OPTION(maskingadjust_short, set->masking_adj_short, 0);\n    if (lame_get_VBR(gfp) == vbr_mt || lame_get_VBR(gfp) == vbr_mtrh) {\n        lame_set_ATHtype(gfp, 5);\n    }\n    SET_OPTION(ATHlower, set->ath_lower, 0);\n    SET_OPTION(ATHcurve, set->ath_curve, -1);\n    SET_OPTION(athaa_sensitivity, set->ath_sensitivity, 0);\n    if (set->interch > 0) {\n        SET_OPTION(interChRatio, set->interch, -1);\n    }\n\n    /* parameters for which there is no proper set/get interface */\n    if (set->safejoint > 0) {\n        (void) lame_set_exp_nspsytune(gfp, lame_get_exp_nspsytune(gfp) | 2);\n    }\n    if (set->sfb21mod > 0) {\n        int const nsp = lame_get_exp_nspsytune(gfp);\n        int const val = (nsp >> 20) & 63;\n        if (val == 0) {\n            int const sf21mod = (set->sfb21mod << 20) | nsp;\n            (void) lame_set_exp_nspsytune(gfp, sf21mod);\n        }\n    }\n    SET__OPTION(msfix, set->msfix, -1);\n\n    if (enforce == 0) {\n        gfp->VBR_q = a;\n        gfp->VBR_q_frac = x;\n    }\n    gfp->internal_flags->cfg.minval = set->minval;\n    gfp->internal_flags->cfg.ATHfixpoint = set->ath_fixpoint;\n}\n\nstatic int\napply_abr_preset(lame_global_flags * gfp, int preset, int enforce)\n{\n    typedef struct {\n        int     abr_kbps;\n        int     quant_comp;\n        int     quant_comp_s;\n        int     safejoint;\n        FLOAT   nsmsfix;\n        FLOAT   st_lrm;      /*short threshold */\n        FLOAT   st_s;\n        FLOAT   scale;\n        FLOAT   masking_adj;\n        FLOAT   ath_lower;\n        FLOAT   ath_curve;\n        FLOAT   interch;\n        int     sfscale;\n    } abr_presets_t;\n\n\n    /* *INDENT-OFF* */\n\n    /* \n     *  Switch mappings for ABR mode\n     */\n    const abr_presets_t abr_switch_map[] = {        \n    /* kbps  quant q_s safejoint nsmsfix st_lrm  st_s  scale   msk ath_lwr ath_curve  interch , sfscale */\n      {  8,     9,  9,        0,      0,  6.60,  145,  0.95,    0,  -30.0,     11,    0.0012,        1}, /*   8, impossible to use in stereo */\n      { 16,     9,  9,        0,      0,  6.60,  145,  0.95,    0,  -25.0,     11,    0.0010,        1}, /*  16 */\n      { 24,     9,  9,        0,      0,  6.60,  145,  0.95,    0,  -20.0,     11,    0.0010,        1}, /*  24 */\n      { 32,     9,  9,        0,      0,  6.60,  145,  0.95,    0,  -15.0,     11,    0.0010,        1}, /*  32 */\n      { 40,     9,  9,        0,      0,  6.60,  145,  0.95,    0,  -10.0,     11,    0.0009,        1}, /*  40 */\n      { 48,     9,  9,        0,      0,  6.60,  145,  0.95,    0,  -10.0,     11,    0.0009,        1}, /*  48 */\n      { 56,     9,  9,        0,      0,  6.60,  145,  0.95,    0,   -6.0,     11,    0.0008,        1}, /*  56 */\n      { 64,     9,  9,        0,      0,  6.60,  145,  0.95,    0,   -2.0,     11,    0.0008,        1}, /*  64 */\n      { 80,     9,  9,        0,      0,  6.60,  145,  0.95,    0,     .0,      8,    0.0007,        1}, /*  80 */\n      { 96,     9,  9,        0,   2.50,  6.60,  145,  0.95,    0,    1.0,      5.5,  0.0006,        1}, /*  96 */\n      {112,     9,  9,        0,   2.25,  6.60,  145,  0.95,    0,    2.0,      4.5,  0.0005,        1}, /* 112 */\n      {128,     9,  9,        0,   1.95,  6.40,  140,  0.95,    0,    3.0,      4,    0.0002,        1}, /* 128 */\n      {160,     9,  9,        1,   1.79,  6.00,  135,  0.95,   -2,    5.0,      3.5,  0,             1}, /* 160 */\n      {192,     9,  9,        1,   1.49,  5.60,  125,  0.97,   -4,    7.0,      3,    0,             0}, /* 192 */\n      {224,     9,  9,        1,   1.25,  5.20,  125,  0.98,   -6,    9.0,      2,    0,             0}, /* 224 */\n      {256,     9,  9,        1,   0.97,  5.20,  125,  1.00,   -8,   10.0,      1,    0,             0}, /* 256 */\n      {320,     9,  9,        1,   0.90,  5.20,  125,  1.00,  -10,   12.0,      0,    0,             0}  /* 320 */\n    };\n\n    /* *INDENT-ON* */\n\n    /* Variables for the ABR stuff */\n    int     r;\n    int     actual_bitrate = preset;\n\n    r = nearestBitrateFullIndex(preset);\n    \n    (void) lame_set_VBR(gfp, vbr_abr);\n    (void) lame_set_VBR_mean_bitrate_kbps(gfp, (actual_bitrate));\n    (void) lame_set_VBR_mean_bitrate_kbps(gfp, min_int(lame_get_VBR_mean_bitrate_kbps(gfp), 320));\n    (void) lame_set_VBR_mean_bitrate_kbps(gfp, max_int(lame_get_VBR_mean_bitrate_kbps(gfp), 8));\n    (void) lame_set_brate(gfp, lame_get_VBR_mean_bitrate_kbps(gfp));\n\n\n    /* parameters for which there is no proper set/get interface */\n    if (abr_switch_map[r].safejoint > 0)\n        (void) lame_set_exp_nspsytune(gfp, lame_get_exp_nspsytune(gfp) | 2); /* safejoint */\n\n    if (abr_switch_map[r].sfscale > 0)\n        (void) lame_set_sfscale(gfp, 1);\n\n\n    SET_OPTION(quant_comp, abr_switch_map[r].quant_comp, -1);\n    SET_OPTION(quant_comp_short, abr_switch_map[r].quant_comp_s, -1);\n\n    SET__OPTION(msfix, abr_switch_map[r].nsmsfix, -1);\n\n    SET_OPTION(short_threshold_lrm, abr_switch_map[r].st_lrm, -1);\n    SET_OPTION(short_threshold_s, abr_switch_map[r].st_s, -1);\n\n    /* ABR seems to have big problems with clipping, especially at low bitrates */\n    /* so we compensate for that here by using a scale value depending on bitrate */\n    lame_set_scale(gfp, lame_get_scale(gfp) * abr_switch_map[r].scale);\n\n    SET_OPTION(maskingadjust, abr_switch_map[r].masking_adj, 0);\n    if (abr_switch_map[r].masking_adj > 0) {\n        SET_OPTION(maskingadjust_short, abr_switch_map[r].masking_adj * .9, 0);\n    }\n    else {\n        SET_OPTION(maskingadjust_short, abr_switch_map[r].masking_adj * 1.1, 0);\n    }\n\n\n    SET_OPTION(ATHlower, abr_switch_map[r].ath_lower, 0);\n    SET_OPTION(ATHcurve, abr_switch_map[r].ath_curve, -1);\n\n    SET_OPTION(interChRatio, abr_switch_map[r].interch, -1);\n\n    (void) abr_switch_map[r].abr_kbps;\n\n    gfp->internal_flags->cfg.minval = 5. * (abr_switch_map[r].abr_kbps / 320.);\n\n    return preset;\n}\n\n\n\nint\napply_preset(lame_global_flags * gfp, int preset, int enforce)\n{\n    /*translate legacy presets */\n    switch (preset) {\n    case R3MIX:\n        {\n            preset = V3;\n            (void) lame_set_VBR(gfp, vbr_mtrh);\n            break;\n        }\n    case MEDIUM:\n    case MEDIUM_FAST:\n        {\n            preset = V4;\n            (void) lame_set_VBR(gfp, vbr_mtrh);\n            break;\n        }\n    case STANDARD:\n    case STANDARD_FAST:\n        {\n            preset = V2;\n            (void) lame_set_VBR(gfp, vbr_mtrh);\n            break;\n        }\n    case EXTREME:\n    case EXTREME_FAST:\n        {\n            preset = V0;\n            (void) lame_set_VBR(gfp, vbr_mtrh);\n            break;\n        }\n    case INSANE:\n        {\n            preset = 320;\n            gfp->preset = preset;\n            (void) apply_abr_preset(gfp, preset, enforce);\n            lame_set_VBR(gfp, vbr_off);\n            return preset;\n        }\n    }\n\n    gfp->preset = preset;\n    {\n        switch (preset) {\n        case V9:\n            apply_vbr_preset(gfp, 9, enforce);\n            return preset;\n        case V8:\n            apply_vbr_preset(gfp, 8, enforce);\n            return preset;\n        case V7:\n            apply_vbr_preset(gfp, 7, enforce);\n            return preset;\n        case V6:\n            apply_vbr_preset(gfp, 6, enforce);\n            return preset;\n        case V5:\n            apply_vbr_preset(gfp, 5, enforce);\n            return preset;\n        case V4:\n            apply_vbr_preset(gfp, 4, enforce);\n            return preset;\n        case V3:\n            apply_vbr_preset(gfp, 3, enforce);\n            return preset;\n        case V2:\n            apply_vbr_preset(gfp, 2, enforce);\n            return preset;\n        case V1:\n            apply_vbr_preset(gfp, 1, enforce);\n            return preset;\n        case V0:\n            apply_vbr_preset(gfp, 0, enforce);\n            return preset;\n        default:\n            break;\n        }\n    }\n    if (8 <= preset && preset <= 320) {\n        return apply_abr_preset(gfp, preset, enforce);\n    }\n\n    gfp->preset = 0;    /*no corresponding preset found */\n    return preset;\n}\n"
  },
  {
    "path": "app/jni/libmp3lame/psymodel.c",
    "content": "/*\n *      psymodel.c\n *\n *      Copyright (c) 1999-2000 Mark Taylor\n *      Copyright (c) 2001-2002 Naoki Shibata\n *      Copyright (c) 2000-2003 Takehiro Tominaga\n *      Copyright (c) 2000-2011 Robert Hegemann\n *      Copyright (c) 2000-2005 Gabriel Bouvigne\n *      Copyright (c) 2000-2005 Alexander Leidinger\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: psymodel.c,v 1.209 2011/05/24 20:45:55 robert Exp $ */\n\n\n/*\nPSYCHO ACOUSTICS\n\n\nThis routine computes the psycho acoustics, delayed by one granule.  \n\nInput: buffer of PCM data (1024 samples).  \n\nThis window should be centered over the 576 sample granule window.\nThe routine will compute the psycho acoustics for\nthis granule, but return the psycho acoustics computed\nfor the *previous* granule.  This is because the block\ntype of the previous granule can only be determined\nafter we have computed the psycho acoustics for the following\ngranule.  \n\nOutput:  maskings and energies for each scalefactor band.\nblock type, PE, and some correlation measures.  \nThe PE is used by CBR modes to determine if extra bits\nfrom the bit reservoir should be used.  The correlation\nmeasures are used to determine mid/side or regular stereo.\n*/\n/*\nNotation:\n\nbarks:  a non-linear frequency scale.  Mapping from frequency to\n        barks is given by freq2bark()\n\nscalefactor bands: The spectrum (frequencies) are broken into \n                   SBMAX \"scalefactor bands\".  Thes bands\n                   are determined by the MPEG ISO spec.  In\n                   the noise shaping/quantization code, we allocate\n                   bits among the partition bands to achieve the\n                   best possible quality\n\npartition bands:   The spectrum is also broken into about\n                   64 \"partition bands\".  Each partition \n                   band is about .34 barks wide.  There are about 2-5\n                   partition bands for each scalefactor band.\n\nLAME computes all psycho acoustic information for each partition\nband.  Then at the end of the computations, this information\nis mapped to scalefactor bands.  The energy in each scalefactor\nband is taken as the sum of the energy in all partition bands\nwhich overlap the scalefactor band.  The maskings can be computed\nin the same way (and thus represent the average masking in that band)\nor by taking the minmum value multiplied by the number of\npartition bands used (which represents a minimum masking in that band).\n*/\n/*\nThe general outline is as follows:\n\n1. compute the energy in each partition band\n2. compute the tonality in each partition band\n3. compute the strength of each partion band \"masker\"\n4. compute the masking (via the spreading function applied to each masker)\n5. Modifications for mid/side masking.  \n\nEach partition band is considiered a \"masker\".  The strength\nof the i'th masker in band j is given by:\n\n    s3(bark(i)-bark(j))*strength(i)\n\nThe strength of the masker is a function of the energy and tonality.\nThe more tonal, the less masking.  LAME uses a simple linear formula\n(controlled by NMT and TMN) which says the strength is given by the\nenergy divided by a linear function of the tonality.\n*/\n/*\ns3() is the \"spreading function\".  It is given by a formula\ndetermined via listening tests.  \n\nThe total masking in the j'th partition band is the sum over\nall maskings i.  It is thus given by the convolution of\nthe strength with s3(), the \"spreading function.\"\n\nmasking(j) = sum_over_i  s3(i-j)*strength(i)  = s3 o strength\n\nwhere \"o\" = convolution operator.  s3 is given by a formula determined\nvia listening tests.  It is normalized so that s3 o 1 = 1.\n\nNote: instead of a simple convolution, LAME also has the\noption of using \"additive masking\"\n\nThe most critical part is step 2, computing the tonality of each\npartition band.  LAME has two tonality estimators.  The first\nis based on the ISO spec, and measures how predictiable the\nsignal is over time.  The more predictable, the more tonal.\nThe second measure is based on looking at the spectrum of\na single granule.  The more peaky the spectrum, the more\ntonal.  By most indications, the latter approach is better.\n\nFinally, in step 5, the maskings for the mid and side\nchannel are possibly increased.  Under certain circumstances,\nnoise in the mid & side channels is assumed to also\nbe masked by strong maskers in the L or R channels.\n\n\nOther data computed by the psy-model:\n\nms_ratio        side-channel / mid-channel masking ratio (for previous granule)\nms_ratio_next   side-channel / mid-channel masking ratio for this granule\n\npercep_entropy[2]     L and R values (prev granule) of PE - A measure of how \n                      much pre-echo is in the previous granule\npercep_entropy_MS[2]  mid and side channel values (prev granule) of percep_entropy\nenergy[4]             L,R,M,S energy in each channel, prev granule\nblocktype_d[2]        block type to use for previous granule\n*/\n\n\n\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n//#include <__clang_cuda_math_forward_declares.h>\n#include <string.h>\n#include <strings.h>\n#include <malloc.h>\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"psymodel.h\"\n#include \"lame_global_flags.h\"\n#include \"fft.h\"\n#include \"lame-analysis.h\"\n\n#define NSFIRLEN 21\n\n#ifdef M_LN10\n#define  LN_TO_LOG10  (M_LN10/10)\n#else\n#define  LN_TO_LOG10  0.2302585093\n#endif\n\n/*\n   L3psycho_anal.  Compute psycho acoustics.\n\n   Data returned to the calling program must be delayed by one \n   granule. \n\n   This is done in two places.  \n   If we do not need to know the blocktype, the copying\n   can be done here at the top of the program: we copy the data for\n   the last granule (computed during the last call) before it is\n   overwritten with the new data.  It looks like this:\n  \n   0. static psymodel_data \n   1. calling_program_data = psymodel_data\n   2. compute psymodel_data\n    \n   For data which needs to know the blocktype, the copying must be\n   done at the end of this loop, and the old values must be saved:\n   \n   0. static psymodel_data_old \n   1. compute psymodel_data\n   2. compute possible block type of this granule\n   3. compute final block type of previous granule based on #2.\n   4. calling_program_data = psymodel_data_old\n   5. psymodel_data_old = psymodel_data\n*/\n\n\n\n\n\n/* psycho_loudness_approx\n   jd - 2001 mar 12\nin:  energy   - BLKSIZE/2 elements of frequency magnitudes ^ 2\n     gfp      - uses out_samplerate, ATHtype (also needed for ATHformula)\nreturns: loudness^2 approximation, a positive value roughly tuned for a value\n         of 1.0 for signals near clipping.\nnotes:   When calibrated, feeding this function binary white noise at sample\n         values +32767 or -32768 should return values that approach 3.\n         ATHformula is used to approximate an equal loudness curve.\nfuture:  Data indicates that the shape of the equal loudness curve varies\n         with intensity.  This function might be improved by using an equal\n         loudness curve shaped for typical playback levels (instead of the\n         ATH, that is shaped for the threshold).  A flexible realization might\n         simply bend the existing ATH curve to achieve the desired shape.\n         However, the potential gain may not be enough to justify an effort.\n*/\nstatic  FLOAT\npsycho_loudness_approx(FLOAT const *energy, FLOAT const *eql_w)\n{\n    int     i;\n    FLOAT   loudness_power;\n\n    loudness_power = 0.0;\n    /* apply weights to power in freq. bands */\n    for (i = 0; i < BLKSIZE / 2; ++i)\n        loudness_power += energy[i] * eql_w[i];\n    loudness_power *= VO_SCALE;\n\n    return loudness_power;\n}\n\n/* mask_add optimization */\n/* init the limit values used to avoid computing log in mask_add when it is not necessary */\n\n/* For example, with i = 10*log10(m2/m1)/10*16         (= log10(m2/m1)*16)\n *\n * abs(i)>8 is equivalent (as i is an integer) to\n * abs(i)>=9\n * i>=9 || i<=-9\n * equivalent to (as i is the biggest integer smaller than log10(m2/m1)*16 \n * or the smallest integer bigger than log10(m2/m1)*16 depending on the sign of log10(m2/m1)*16)\n * log10(m2/m1)>=9/16 || log10(m2/m1)<=-9/16\n * exp10 is strictly increasing thus this is equivalent to\n * m2/m1 >= 10^(9/16) || m2/m1<=10^(-9/16) which are comparisons to constants\n */\n\n\n#define I1LIMIT 8       /* as in if(i>8)  */\n#define I2LIMIT 23      /* as in if(i>24) -> changed 23 */\n#define MLIMIT  15      /* as in if(m<15) */\n\nstatic FLOAT ma_max_i1;\nstatic FLOAT ma_max_i2;\nstatic FLOAT ma_max_m;\n\n    /*This is the masking table:\n       According to tonality, values are going from 0dB (TMN)\n       to 9.3dB (NMT).\n       After additive masking computation, 8dB are added, so\n       final values are going from 8dB to 17.3dB\n     */\nstatic const FLOAT tab[] = {\n    1.0 /*pow(10, -0) */ ,\n    0.79433 /*pow(10, -0.1) */ ,\n    0.63096 /*pow(10, -0.2) */ ,\n    0.63096 /*pow(10, -0.2) */ ,\n    0.63096 /*pow(10, -0.2) */ ,\n    0.63096 /*pow(10, -0.2) */ ,\n    0.63096 /*pow(10, -0.2) */ ,\n    0.25119 /*pow(10, -0.6) */ ,\n    0.11749             /*pow(10, -0.93) */\n};\n\nstatic const int tab_mask_add_delta[] = { 2, 2, 2, 1, 1, 1, 0, 0, -1 };\n#define STATIC_ASSERT_EQUAL_DIMENSION(A,B) {extern char static_assert_##A[dimension_of(A) == dimension_of(B) ? 1 : -1];(void) static_assert_##A;}\n\ninline static int\nmask_add_delta(int i)\n{\n    STATIC_ASSERT_EQUAL_DIMENSION(tab_mask_add_delta,tab);\n    assert(i < (int)dimension_of(tab));\n    return tab_mask_add_delta[i];\n}\n\n\nstatic void\ninit_mask_add_max_values(void)\n{\n    ma_max_i1 = pow(10, (I1LIMIT + 1) / 16.0);\n    ma_max_i2 = pow(10, (I2LIMIT + 1) / 16.0);\n    ma_max_m = pow(10, (MLIMIT) / 10.0);\n}\n\n\n\n\n/* addition of simultaneous masking   Naoki Shibata 2000/7 */\ninline static FLOAT\nvbrpsy_mask_add(FLOAT m1, FLOAT m2, int b, int delta)\n{\n    static const FLOAT table2[] = {\n        1.33352 * 1.33352, 1.35879 * 1.35879, 1.38454 * 1.38454, 1.39497 * 1.39497,\n        1.40548 * 1.40548, 1.3537 * 1.3537, 1.30382 * 1.30382, 1.22321 * 1.22321,\n        1.14758 * 1.14758,\n        1\n    };\n\n    FLOAT   ratio;\n\n    if (m1 < 0) {\n        m1 = 0;\n    }\n    if (m2 < 0) {\n        m2 = 0;\n    }\n    if (m1 <= 0) {\n        return m2;\n    }\n    if (m2 <= 0) {\n        return m1;\n    }\n    if (m2 > m1) {\n        ratio = m2 / m1;\n    }\n    else {\n        ratio = m1 / m2;\n    }\n    if (abs(b) <= delta) {       /* approximately, 1 bark = 3 partitions */\n        /* originally 'if(i > 8)' */\n        if (ratio >= ma_max_i1) {\n            return m1 + m2;\n        }\n        else {\n            int     i = (int) (FAST_LOG10_X(ratio, 16.0f));\n            return (m1 + m2) * table2[i];\n        }\n    }\n    if (ratio < ma_max_i2) {\n        return m1 + m2;\n    }\n    if (m1 < m2) {\n        m1 = m2;\n    }\n    return m1;\n}\n\n\n/* short block threshold calculation (part 2)\n\n    partition band bo_s[sfb] is at the transition from scalefactor\n    band sfb to the next one sfb+1; enn and thmm have to be split\n    between them\n*/\nstatic void\nconvert_partition2scalefac(PsyConst_CB2SB_t const *const gd, FLOAT const *eb, FLOAT const *thr,\n                           FLOAT enn_out[], FLOAT thm_out[])\n{\n    FLOAT   enn, thmm;\n    int     sb, b, n = gd->n_sb;\n    enn = thmm = 0.0f;\n    for (sb = b = 0; sb < n; ++b, ++sb) {\n        int const bo_sb = gd->bo[sb];\n        int const npart = gd->npart;\n        int const b_lim = bo_sb < npart ? bo_sb : npart;\n        while (b < b_lim) {\n            assert(eb[b] >= 0); /* iff failed, it may indicate some index error elsewhere */\n            assert(thr[b] >= 0);\n            enn += eb[b];\n            thmm += thr[b];\n            b++;\n        }\n        if (b >= npart) {\n            enn_out[sb] = enn;\n            thm_out[sb] = thmm;\n            ++sb;\n            break;\n        }\n        assert(eb[b] >= 0); /* iff failed, it may indicate some index error elsewhere */\n        assert(thr[b] >= 0);\n        {\n            /* at transition sfb -> sfb+1 */\n            FLOAT const w_curr = gd->bo_weight[sb];\n            FLOAT const w_next = 1.0f - w_curr;\n            enn += w_curr * eb[b];\n            thmm += w_curr * thr[b];\n            enn_out[sb] = enn;\n            thm_out[sb] = thmm;\n            enn = w_next * eb[b];\n            thmm = w_next * thr[b];\n        }\n    }\n    /* zero initialize the rest */\n    for (; sb < n; ++sb) {\n        enn_out[sb] = 0;\n        thm_out[sb] = 0;\n    }\n}\n\nstatic void\nconvert_partition2scalefac_s(lame_internal_flags * gfc, FLOAT const *eb, FLOAT const *thr, int chn,\n                             int sblock)\n{\n    PsyStateVar_t *const psv = &gfc->sv_psy;\n    PsyConst_CB2SB_t const *const gds = &gfc->cd_psy->s;\n    FLOAT   enn[SBMAX_s], thm[SBMAX_s];\n    int     sb;\n    convert_partition2scalefac(gds, eb, thr, enn, thm);\n    for (sb = 0; sb < SBMAX_s; ++sb) {\n        psv->en[chn].s[sb][sblock] = enn[sb];\n        psv->thm[chn].s[sb][sblock] = thm[sb];\n    }\n}\n\n/* longblock threshold calculation (part 2) */\nstatic void\nconvert_partition2scalefac_l(lame_internal_flags * gfc, FLOAT const *eb, FLOAT const *thr, int chn)\n{\n    PsyStateVar_t *const psv = &gfc->sv_psy;\n    PsyConst_CB2SB_t const *const gdl = &gfc->cd_psy->l;\n    FLOAT  *enn = &psv->en[chn].l[0];\n    FLOAT  *thm = &psv->thm[chn].l[0];\n    convert_partition2scalefac(gdl, eb, thr, enn, thm);\n}\n\nstatic void\nconvert_partition2scalefac_l_to_s(lame_internal_flags * gfc, FLOAT const *eb, FLOAT const *thr,\n                                  int chn)\n{\n    PsyStateVar_t *const psv = &gfc->sv_psy;\n    PsyConst_CB2SB_t const *const gds = &gfc->cd_psy->l_to_s;\n    FLOAT   enn[SBMAX_s], thm[SBMAX_s];\n    int     sb, sblock;\n    convert_partition2scalefac(gds, eb, thr, enn, thm);\n    for (sb = 0; sb < SBMAX_s; ++sb) {\n        FLOAT const scale = 1. / 64.f;\n        FLOAT const tmp_enn = enn[sb];\n        FLOAT const tmp_thm = thm[sb] * scale;\n        for (sblock = 0; sblock < 3; ++sblock) {\n            psv->en[chn].s[sb][sblock] = tmp_enn;\n            psv->thm[chn].s[sb][sblock] = tmp_thm;\n        }\n    }\n}\n\n\n\nstatic inline FLOAT\nNS_INTERP(FLOAT x, FLOAT y, FLOAT r)\n{\n    /* was pow((x),(r))*pow((y),1-(r)) */\n    if (r >= 1.0f)\n        return x;       /* 99.7% of the time */\n    if (r <= 0.0f)\n        return y;\n    if (y > 0.0f)\n        return powf(x / y, r) * y; /* rest of the time */\n    return 0.0f;        /* never happens */\n}\n\n\n\nstatic  FLOAT\npecalc_s(III_psy_ratio const *mr, FLOAT masking_lower)\n{\n    FLOAT   pe_s;\n    static const FLOAT regcoef_s[] = {\n        11.8,           /* these values are tuned only for 44.1kHz... */\n        13.6,\n        17.2,\n        32,\n        46.5,\n        51.3,\n        57.5,\n        67.1,\n        71.5,\n        84.6,\n        97.6,\n        130,\n/*      255.8 */\n    };\n    unsigned int sb, sblock;\n\n    pe_s = 1236.28f / 4;\n    for (sb = 0; sb < SBMAX_s - 1; sb++) {\n        for (sblock = 0; sblock < 3; sblock++) {\n            FLOAT const thm = mr->thm.s[sb][sblock];\n            assert(sb < dimension_of(regcoef_s));\n            if (thm > 0.0f) {\n                FLOAT const x = thm * masking_lower;\n                FLOAT const en = mr->en.s[sb][sblock];\n                if (en > x) {\n                    if (en > x * 1e10f) {\n                        pe_s += regcoef_s[sb] * (10.0f * LOG10);\n                    }\n                    else {\n                        assert(x > 0);\n                        pe_s += regcoef_s[sb] * FAST_LOG10(en / x);\n                    }\n                }\n            }\n        }\n    }\n\n    return pe_s;\n}\n\nstatic  FLOAT\npecalc_l(III_psy_ratio const *mr, FLOAT masking_lower)\n{\n    FLOAT   pe_l;\n    static const FLOAT regcoef_l[] = {\n        6.8,            /* these values are tuned only for 44.1kHz... */\n        5.8,\n        5.8,\n        6.4,\n        6.5,\n        9.9,\n        12.1,\n        14.4,\n        15,\n        18.9,\n        21.6,\n        26.9,\n        34.2,\n        40.2,\n        46.8,\n        56.5,\n        60.7,\n        73.9,\n        85.7,\n        93.4,\n        126.1,\n/*      241.3 */\n    };\n    unsigned int sb;\n\n    pe_l = 1124.23f / 4;\n    for (sb = 0; sb < SBMAX_l - 1; sb++) {\n        FLOAT const thm = mr->thm.l[sb];\n        assert(sb < dimension_of(regcoef_l));\n        if (thm > 0.0f) {\n            FLOAT const x = thm * masking_lower;\n            FLOAT const en = mr->en.l[sb];\n            if (en > x) {\n                if (en > x * 1e10f) {\n                    pe_l += regcoef_l[sb] * (10.0f * LOG10);\n                }\n                else {\n                    assert(x > 0);\n                    pe_l += regcoef_l[sb] * FAST_LOG10(en / x);\n                }\n            }\n        }\n    }\n\n    return pe_l;\n}\n\n\nstatic void\ncalc_energy(PsyConst_CB2SB_t const *l, FLOAT const *fftenergy, FLOAT * eb, FLOAT * max, FLOAT * avg)\n{\n    int     b, j;\n\n    for (b = j = 0; b < l->npart; ++b) {\n        FLOAT   ebb = 0, m = 0;\n        int     i;\n        for (i = 0; i < l->numlines[b]; ++i, ++j) {\n            FLOAT const el = fftenergy[j];\n            assert(el >= 0);\n            ebb += el;\n            if (m < el)\n                m = el;\n        }\n        eb[b] = ebb;\n        max[b] = m;\n        avg[b] = ebb * l->rnumlines[b];\n        assert(l->rnumlines[b] >= 0);\n        assert(ebb >= 0);\n        assert(eb[b] >= 0);\n        assert(max[b] >= 0);\n        assert(avg[b] >= 0);\n    }\n}\n\n\nstatic void\ncalc_mask_index_l(lame_internal_flags const *gfc, FLOAT const *max,\n                  FLOAT const *avg, unsigned char *mask_idx)\n{\n    PsyConst_CB2SB_t const *const gdl = &gfc->cd_psy->l;\n    FLOAT   m, a;\n    int     b, k;\n    int const last_tab_entry = sizeof(tab) / sizeof(tab[0]) - 1;\n    b = 0;\n    a = avg[b] + avg[b + 1];\n    assert(a >= 0);\n    if (a > 0.0f) {\n        m = max[b];\n        if (m < max[b + 1])\n            m = max[b + 1];\n        assert((gdl->numlines[b] + gdl->numlines[b + 1] - 1) > 0);\n        a = 20.0f * (m * 2.0f - a)\n            / (a * (gdl->numlines[b] + gdl->numlines[b + 1] - 1));\n        k = (int) a;\n        if (k > last_tab_entry)\n            k = last_tab_entry;\n        mask_idx[b] = k;\n    }\n    else {\n        mask_idx[b] = 0;\n    }\n\n    for (b = 1; b < gdl->npart - 1; b++) {\n        a = avg[b - 1] + avg[b] + avg[b + 1];\n        assert(a >= 0);\n        if (a > 0.0f) {\n            m = max[b - 1];\n            if (m < max[b])\n                m = max[b];\n            if (m < max[b + 1])\n                m = max[b + 1];\n            assert((gdl->numlines[b - 1] + gdl->numlines[b] + gdl->numlines[b + 1] - 1) > 0);\n            a = 20.0f * (m * 3.0f - a)\n                / (a * (gdl->numlines[b - 1] + gdl->numlines[b] + gdl->numlines[b + 1] - 1));\n            k = (int) a;\n            if (k > last_tab_entry)\n                k = last_tab_entry;\n            mask_idx[b] = k;\n        }\n        else {\n            mask_idx[b] = 0;\n        }\n    }\n    assert(b > 0);\n    assert(b == gdl->npart - 1);\n\n    a = avg[b - 1] + avg[b];\n    assert(a >= 0);\n    if (a > 0.0f) {\n        m = max[b - 1];\n        if (m < max[b])\n            m = max[b];\n        assert((gdl->numlines[b - 1] + gdl->numlines[b] - 1) > 0);\n        a = 20.0f * (m * 2.0f - a)\n            / (a * (gdl->numlines[b - 1] + gdl->numlines[b] - 1));\n        k = (int) a;\n        if (k > last_tab_entry)\n            k = last_tab_entry;\n        mask_idx[b] = k;\n    }\n    else {\n        mask_idx[b] = 0;\n    }\n    assert(b == (gdl->npart - 1));\n}\n\n\nstatic void\nvbrpsy_compute_fft_l(lame_internal_flags * gfc, const sample_t * const buffer[2], int chn,\n                     int gr_out, FLOAT fftenergy[HBLKSIZE], FLOAT(*wsamp_l)[BLKSIZE])\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    PsyStateVar_t *psv = &gfc->sv_psy;\n    plotting_data *plt = cfg->analysis ? gfc->pinfo : 0;\n    int     j;\n\n    if (chn < 2) {\n        fft_long(gfc, *wsamp_l, chn, buffer);\n    }\n    else if (chn == 2) {\n        FLOAT const sqrt2_half = SQRT2 * 0.5f;\n        /* FFT data for mid and side channel is derived from L & R */\n        for (j = BLKSIZE - 1; j >= 0; --j) {\n            FLOAT const l = wsamp_l[0][j];\n            FLOAT const r = wsamp_l[1][j];\n            wsamp_l[0][j] = (l + r) * sqrt2_half;\n            wsamp_l[1][j] = (l - r) * sqrt2_half;\n        }\n    }\n\n    /*********************************************************************\n    *  compute energies\n    *********************************************************************/\n    fftenergy[0] = wsamp_l[0][0];\n    fftenergy[0] *= fftenergy[0];\n\n    for (j = BLKSIZE / 2 - 1; j >= 0; --j) {\n        FLOAT const re = (*wsamp_l)[BLKSIZE / 2 - j];\n        FLOAT const im = (*wsamp_l)[BLKSIZE / 2 + j];\n        fftenergy[BLKSIZE / 2 - j] = (re * re + im * im) * 0.5f;\n    }\n    /* total energy */\n    {\n        FLOAT   totalenergy = 0.0f;\n        for (j = 11; j < HBLKSIZE; j++)\n            totalenergy += fftenergy[j];\n\n        psv->tot_ener[chn] = totalenergy;\n    }\n\n    if (plt) {\n        for (j = 0; j < HBLKSIZE; j++) {\n            plt->energy[gr_out][chn][j] = plt->energy_save[chn][j];\n            plt->energy_save[chn][j] = fftenergy[j];\n        }\n    }\n}\n\n\nstatic void\nvbrpsy_compute_fft_s(lame_internal_flags const *gfc, const sample_t * const buffer[2], int chn,\n                     int sblock, FLOAT(*fftenergy_s)[HBLKSIZE_s], FLOAT(*wsamp_s)[3][BLKSIZE_s])\n{\n    int     j;\n\n    if (sblock == 0 && chn < 2) {\n        fft_short(gfc, *wsamp_s, chn, buffer);\n    }\n    if (chn == 2) {\n        FLOAT const sqrt2_half = SQRT2 * 0.5f;\n        /* FFT data for mid and side channel is derived from L & R */\n        for (j = BLKSIZE_s - 1; j >= 0; --j) {\n            FLOAT const l = wsamp_s[0][sblock][j];\n            FLOAT const r = wsamp_s[1][sblock][j];\n            wsamp_s[0][sblock][j] = (l + r) * sqrt2_half;\n            wsamp_s[1][sblock][j] = (l - r) * sqrt2_half;\n        }\n    }\n\n    /*********************************************************************\n    *  compute energies\n    *********************************************************************/\n    fftenergy_s[sblock][0] = (*wsamp_s)[sblock][0];\n    fftenergy_s[sblock][0] *= fftenergy_s[sblock][0];\n    for (j = BLKSIZE_s / 2 - 1; j >= 0; --j) {\n        FLOAT const re = (*wsamp_s)[sblock][BLKSIZE_s / 2 - j];\n        FLOAT const im = (*wsamp_s)[sblock][BLKSIZE_s / 2 + j];\n        fftenergy_s[sblock][BLKSIZE_s / 2 - j] = (re * re + im * im) * 0.5f;\n    }\n}\n\n\n    /*********************************************************************\n    * compute loudness approximation (used for ATH auto-level adjustment) \n    *********************************************************************/\nstatic void\nvbrpsy_compute_loudness_approximation_l(lame_internal_flags * gfc, int gr_out, int chn,\n                                        const FLOAT fftenergy[HBLKSIZE])\n{\n    PsyStateVar_t *psv = &gfc->sv_psy;\n    if (chn < 2) {      /*no loudness for mid/side ch */\n        gfc->ov_psy.loudness_sq[gr_out][chn] = psv->loudness_sq_save[chn];\n        psv->loudness_sq_save[chn] = psycho_loudness_approx(fftenergy, gfc->ATH->eql_w);\n    }\n}\n\n\n    /**********************************************************************\n    *  Apply HPF of fs/4 to the input signal.\n    *  This is used for attack detection / handling.\n    **********************************************************************/\nstatic void\nvbrpsy_attack_detection(lame_internal_flags * gfc, const sample_t * const buffer[2], int gr_out,\n                        III_psy_ratio masking_ratio[2][2], III_psy_ratio masking_MS_ratio[2][2],\n                        FLOAT energy[4], FLOAT sub_short_factor[4][3], int ns_attacks[4][4],\n                        int uselongblock[2])\n{\n    FLOAT   ns_hpfsmpl[2][576];\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    PsyStateVar_t *const psv = &gfc->sv_psy;\n    plotting_data *plt = cfg->analysis ? gfc->pinfo : 0;\n    int const n_chn_out = cfg->channels_out;\n    /* chn=2 and 3 = Mid and Side channels */\n    int const n_chn_psy = (cfg->mode == JOINT_STEREO) ? 4 : n_chn_out;\n    int     chn, i, j;\n\n    memset(&ns_hpfsmpl[0][0], 0, sizeof(ns_hpfsmpl));\n    /* Don't copy the input buffer into a temporary buffer */\n    /* unroll the loop 2 times */\n    for (chn = 0; chn < n_chn_out; chn++) {\n        static const FLOAT fircoef[] = {\n            -8.65163e-18 * 2, -0.00851586 * 2, -6.74764e-18 * 2, 0.0209036 * 2,\n            -3.36639e-17 * 2, -0.0438162 * 2, -1.54175e-17 * 2, 0.0931738 * 2,\n            -5.52212e-17 * 2, -0.313819 * 2\n        };\n        /* apply high pass filter of fs/4 */\n        const sample_t *const firbuf = &buffer[chn][576 - 350 - NSFIRLEN + 192];\n        assert(dimension_of(fircoef) == ((NSFIRLEN - 1) / 2));\n        for (i = 0; i < 576; i++) {\n            FLOAT   sum1, sum2;\n            sum1 = firbuf[i + 10];\n            sum2 = 0.0;\n            for (j = 0; j < ((NSFIRLEN - 1) / 2) - 1; j += 2) {\n                sum1 += fircoef[j] * (firbuf[i + j] + firbuf[i + NSFIRLEN - j]);\n                sum2 += fircoef[j + 1] * (firbuf[i + j + 1] + firbuf[i + NSFIRLEN - j - 1]);\n            }\n            ns_hpfsmpl[chn][i] = sum1 + sum2;\n        }\n        masking_ratio[gr_out][chn].en = psv->en[chn];\n        masking_ratio[gr_out][chn].thm = psv->thm[chn];\n        if (n_chn_psy > 2) {\n            /* MS maskings  */\n            /*percep_MS_entropy         [chn-2]     = gfc -> pe  [chn];  */\n            masking_MS_ratio[gr_out][chn].en = psv->en[chn + 2];\n            masking_MS_ratio[gr_out][chn].thm = psv->thm[chn + 2];\n        }\n    }\n    for (chn = 0; chn < n_chn_psy; chn++) {\n        FLOAT   attack_intensity[12];\n        FLOAT   en_subshort[12];\n        FLOAT   en_short[4] = { 0, 0, 0, 0 };\n        FLOAT const *pf = ns_hpfsmpl[chn & 1];\n        int     ns_uselongblock = 1;\n\n        if (chn == 2) {\n            for (i = 0, j = 576; j > 0; ++i, --j) {\n                FLOAT const l = ns_hpfsmpl[0][i];\n                FLOAT const r = ns_hpfsmpl[1][i];\n                ns_hpfsmpl[0][i] = l + r;\n                ns_hpfsmpl[1][i] = l - r;\n            }\n        }\n        /*************************************************************** \n        * determine the block type (window type)\n        ***************************************************************/\n        /* calculate energies of each sub-shortblocks */\n        for (i = 0; i < 3; i++) {\n            en_subshort[i] = psv->last_en_subshort[chn][i + 6];\n            assert(psv->last_en_subshort[chn][i + 4] > 0);\n            attack_intensity[i] = en_subshort[i] / psv->last_en_subshort[chn][i + 4];\n            en_short[0] += en_subshort[i];\n        }\n\n        for (i = 0; i < 9; i++) {\n            FLOAT const *const pfe = pf + 576 / 9;\n            FLOAT   p = 1.;\n            for (; pf < pfe; pf++)\n                if (p < fabs(*pf))\n                    p = fabs(*pf);\n            psv->last_en_subshort[chn][i] = en_subshort[i + 3] = p;\n            en_short[1 + i / 3] += p;\n            if (p > en_subshort[i + 3 - 2]) {\n                assert(en_subshort[i + 3 - 2] > 0);\n                p = p / en_subshort[i + 3 - 2];\n            }\n            else if (en_subshort[i + 3 - 2] > p * 10.0f) {\n                assert(p > 0);\n                p = en_subshort[i + 3 - 2] / (p * 10.0f);\n            }\n            else {\n                p = 0.0;\n            }\n            attack_intensity[i + 3] = p;\n        }\n\n        /* pulse like signal detection for fatboy.wav and so on */\n        for (i = 0; i < 3; ++i) {\n            FLOAT const enn =\n                en_subshort[i * 3 + 3] + en_subshort[i * 3 + 4] + en_subshort[i * 3 + 5];\n            FLOAT   factor = 1.f;\n            if (en_subshort[i * 3 + 5] * 6 < enn) {\n                factor *= 0.5f;\n                if (en_subshort[i * 3 + 4] * 6 < enn) {\n                    factor *= 0.5f;\n                }\n            }\n            sub_short_factor[chn][i] = factor;\n        }\n\n        if (plt) {\n            FLOAT   x = attack_intensity[0];\n            for (i = 1; i < 12; i++) {\n                if (x < attack_intensity[i]) {\n                    x = attack_intensity[i];\n                }\n            }\n            plt->ers[gr_out][chn] = plt->ers_save[chn];\n            plt->ers_save[chn] = x;\n        }\n\n        /* compare energies between sub-shortblocks */\n        {\n            FLOAT   x = gfc->cd_psy->attack_threshold[chn];\n            for (i = 0; i < 12; i++) {\n                if (ns_attacks[chn][i / 3] == 0) {\n                    if (attack_intensity[i] > x) {\n                        ns_attacks[chn][i / 3] = (i % 3) + 1;\n                    }\n                }\n            }\n        }\n        /* should have energy change between short blocks, in order to avoid periodic signals */\n        /* Good samples to show the effect are Trumpet test songs */\n        /* GB: tuned (1) to avoid too many short blocks for test sample TRUMPET */\n        /* RH: tuned (2) to let enough short blocks through for test sample FSOL and SNAPS */\n        for (i = 1; i < 4; i++) {\n            FLOAT const u = en_short[i - 1];\n            FLOAT const v = en_short[i];\n            FLOAT const m = Max(u, v);\n            if (m < 40000) { /* (2) */\n                if (u < 1.7f * v && v < 1.7f * u) { /* (1) */\n                    if (i == 1 && ns_attacks[chn][0] <= ns_attacks[chn][i]) {\n                        ns_attacks[chn][0] = 0;\n                    }\n                    ns_attacks[chn][i] = 0;\n                }\n            }\n        }\n\n        if (ns_attacks[chn][0] <= psv->last_attacks[chn]) {\n            ns_attacks[chn][0] = 0;\n        }\n\n        if (psv->last_attacks[chn] == 3 ||\n            ns_attacks[chn][0] + ns_attacks[chn][1] + ns_attacks[chn][2] + ns_attacks[chn][3]) {\n            ns_uselongblock = 0;\n\n            if (ns_attacks[chn][1] && ns_attacks[chn][0]) {\n                ns_attacks[chn][1] = 0;\n            }\n            if (ns_attacks[chn][2] && ns_attacks[chn][1]) {\n                ns_attacks[chn][2] = 0;\n            }\n            if (ns_attacks[chn][3] && ns_attacks[chn][2]) {\n                ns_attacks[chn][3] = 0;\n            }\n        }\n\n        if (chn < 2) {\n            uselongblock[chn] = ns_uselongblock;\n        }\n        else {\n            if (ns_uselongblock == 0) {\n                uselongblock[0] = uselongblock[1] = 0;\n            }\n        }\n\n        /* there is a one granule delay.  Copy maskings computed last call\n         * into masking_ratio to return to calling program.\n         */\n        energy[chn] = psv->tot_ener[chn];\n    }\n}\n\n\nstatic void\nvbrpsy_skip_masking_s(lame_internal_flags * gfc, int chn, int sblock)\n{\n    if (sblock == 0) {\n        FLOAT  *nbs2 = &gfc->sv_psy.nb_s2[chn][0];\n        FLOAT  *nbs1 = &gfc->sv_psy.nb_s1[chn][0];\n        int const n = gfc->cd_psy->s.npart;\n        int     b;\n        for (b = 0; b < n; b++) {\n            nbs2[b] = nbs1[b];\n        }\n    }\n}\n\n\nstatic void\nvbrpsy_calc_mask_index_s(lame_internal_flags const *gfc, FLOAT const *max,\n                         FLOAT const *avg, unsigned char *mask_idx)\n{\n    PsyConst_CB2SB_t const *const gds = &gfc->cd_psy->s;\n    FLOAT   m, a;\n    int     b, k;\n    int const last_tab_entry = dimension_of(tab) - 1;\n    b = 0;\n    a = avg[b] + avg[b + 1];\n    assert(a >= 0);\n    if (a > 0.0f) {\n        m = max[b];\n        if (m < max[b + 1])\n            m = max[b + 1];\n        assert((gds->numlines[b] + gds->numlines[b + 1] - 1) > 0);\n        a = 20.0f * (m * 2.0f - a)\n            / (a * (gds->numlines[b] + gds->numlines[b + 1] - 1));\n        k = (int) a;\n        if (k > last_tab_entry)\n            k = last_tab_entry;\n        mask_idx[b] = k;\n    }\n    else {\n        mask_idx[b] = 0;\n    }\n\n    for (b = 1; b < gds->npart - 1; b++) {\n        a = avg[b - 1] + avg[b] + avg[b + 1];\n        assert(b + 1 < gds->npart);\n        assert(a >= 0);\n        if (a > 0.0) {\n            m = max[b - 1];\n            if (m < max[b])\n                m = max[b];\n            if (m < max[b + 1])\n                m = max[b + 1];\n            assert((gds->numlines[b - 1] + gds->numlines[b] + gds->numlines[b + 1] - 1) > 0);\n            a = 20.0f * (m * 3.0f - a)\n                / (a * (gds->numlines[b - 1] + gds->numlines[b] + gds->numlines[b + 1] - 1));\n            k = (int) a;\n            if (k > last_tab_entry)\n                k = last_tab_entry;\n            mask_idx[b] = k;\n        }\n        else {\n            mask_idx[b] = 0;\n        }\n    }\n    assert(b > 0);\n    assert(b == gds->npart - 1);\n\n    a = avg[b - 1] + avg[b];\n    assert(a >= 0);\n    if (a > 0.0f) {\n        m = max[b - 1];\n        if (m < max[b])\n            m = max[b];\n        assert((gds->numlines[b - 1] + gds->numlines[b] - 1) > 0);\n        a = 20.0f * (m * 2.0f - a)\n            / (a * (gds->numlines[b - 1] + gds->numlines[b] - 1));\n        k = (int) a;\n        if (k > last_tab_entry)\n            k = last_tab_entry;\n        mask_idx[b] = k;\n    }\n    else {\n        mask_idx[b] = 0;\n    }\n    assert(b == (gds->npart - 1));\n}\n\n\nstatic void\nvbrpsy_compute_masking_s(lame_internal_flags * gfc, const FLOAT(*fftenergy_s)[HBLKSIZE_s],\n                         FLOAT * eb, FLOAT * thr, int chn, int sblock)\n{\n    PsyStateVar_t *const psv = &gfc->sv_psy;\n    PsyConst_CB2SB_t const *const gds = &gfc->cd_psy->s;\n    FLOAT   max[CBANDS], avg[CBANDS];\n    int     i, j, b;\n    unsigned char mask_idx_s[CBANDS];\n\n    memset(max, 0, sizeof(max));\n    memset(avg, 0, sizeof(avg));\n\n    for (b = j = 0; b < gds->npart; ++b) {\n        FLOAT   ebb = 0, m = 0;\n        int const n = gds->numlines[b];\n        for (i = 0; i < n; ++i, ++j) {\n            FLOAT const el = fftenergy_s[sblock][j];\n            ebb += el;\n            if (m < el)\n                m = el;\n        }\n        eb[b] = ebb;\n        assert(ebb >= 0);\n        max[b] = m;\n        assert(n > 0);\n        avg[b] = ebb * gds->rnumlines[b];\n        assert(avg[b] >= 0);\n    }\n    assert(b == gds->npart);\n    assert(j == 129);\n    vbrpsy_calc_mask_index_s(gfc, max, avg, mask_idx_s);\n    for (j = b = 0; b < gds->npart; b++) {\n        int     kk = gds->s3ind[b][0];\n        int const last = gds->s3ind[b][1];\n        int const delta = mask_add_delta(mask_idx_s[b]);\n        int     dd, dd_n;\n        FLOAT   x, ecb, avg_mask;\n        FLOAT const masking_lower = gds->masking_lower[b] * gfc->sv_qnt.masking_lower;\n\n        dd = mask_idx_s[kk];\n        dd_n = 1;\n        ecb = gds->s3[j] * eb[kk] * tab[mask_idx_s[kk]];\n        ++j, ++kk;\n        while (kk <= last) {\n            dd += mask_idx_s[kk];\n            dd_n += 1;\n            x = gds->s3[j] * eb[kk] * tab[mask_idx_s[kk]];\n            ecb = vbrpsy_mask_add(ecb, x, kk - b, delta);\n            ++j, ++kk;\n        }\n        dd = (1 + 2 * dd) / (2 * dd_n);\n        avg_mask = tab[dd] * 0.5f;\n        ecb *= avg_mask;\n#if 0                   /* we can do PRE ECHO control now here, or do it later */\n        if (psv->blocktype_old[chn & 0x01] == SHORT_TYPE) {\n            /* limit calculated threshold by even older granule */\n            FLOAT const t1 = rpelev_s * psv->nb_s1[chn][b];\n            FLOAT const t2 = rpelev2_s * psv->nb_s2[chn][b];\n            FLOAT const tm = (t2 > 0) ? Min(ecb, t2) : ecb;\n            thr[b] = (t1 > 0) ? NS_INTERP(Min(tm, t1), ecb, 0.6) : ecb;\n        }\n        else {\n            /* limit calculated threshold by older granule */\n            FLOAT const t1 = rpelev_s * psv->nb_s1[chn][b];\n            thr[b] = (t1 > 0) ? NS_INTERP(Min(ecb, t1), ecb, 0.6) : ecb;\n        }\n#else /* we do it later */\n        thr[b] = ecb;\n#endif\n        psv->nb_s2[chn][b] = psv->nb_s1[chn][b];\n        psv->nb_s1[chn][b] = ecb;\n        {\n            /*  if THR exceeds EB, the quantization routines will take the difference\n             *  from other bands. in case of strong tonal samples (tonaltest.wav)\n             *  this leads to heavy distortions. that's why we limit THR here.\n             */\n            x = max[b];\n            x *= gds->minval[b];\n            x *= avg_mask;\n            if (thr[b] > x) {\n                thr[b] = x;\n            }\n        }\n        if (masking_lower > 1) {\n            thr[b] *= masking_lower;\n        }\n        if (thr[b] > eb[b]) {\n            thr[b] = eb[b];\n        }\n        if (masking_lower < 1) {\n            thr[b] *= masking_lower;\n        }\n\n        assert(thr[b] >= 0);\n    }\n    for (; b < CBANDS; ++b) {\n        eb[b] = 0;\n        thr[b] = 0;\n    }\n}\n\n\nstatic void\nvbrpsy_compute_masking_l(lame_internal_flags * gfc, const FLOAT fftenergy[HBLKSIZE],\n                         FLOAT eb_l[CBANDS], FLOAT thr[CBANDS], int chn)\n{\n    PsyStateVar_t *const psv = &gfc->sv_psy;\n    PsyConst_CB2SB_t const *const gdl = &gfc->cd_psy->l;\n    FLOAT   max[CBANDS], avg[CBANDS];\n    unsigned char mask_idx_l[CBANDS + 2];\n    int     k, b;\n\n /*********************************************************************\n    *    Calculate the energy and the tonality of each partition.\n *********************************************************************/\n    calc_energy(gdl, fftenergy, eb_l, max, avg);\n    calc_mask_index_l(gfc, max, avg, mask_idx_l);\n\n /*********************************************************************\n    *      convolve the partitioned energy and unpredictability\n    *      with the spreading function, s3_l[b][k]\n ********************************************************************/\n    k = 0;\n    for (b = 0; b < gdl->npart; b++) {\n        FLOAT   x, ecb, avg_mask, t;\n        FLOAT const masking_lower = gdl->masking_lower[b] * gfc->sv_qnt.masking_lower;\n        /* convolve the partitioned energy with the spreading function */\n        int     kk = gdl->s3ind[b][0];\n        int const last = gdl->s3ind[b][1];\n        int const delta = mask_add_delta(mask_idx_l[b]);\n        int     dd = 0, dd_n = 0;\n\n        dd = mask_idx_l[kk];\n        dd_n += 1;\n        ecb = gdl->s3[k] * eb_l[kk] * tab[mask_idx_l[kk]];\n        ++k, ++kk;\n        while (kk <= last) {\n            dd += mask_idx_l[kk];\n            dd_n += 1;\n            x = gdl->s3[k] * eb_l[kk] * tab[mask_idx_l[kk]];\n            t = vbrpsy_mask_add(ecb, x, kk - b, delta);\n#if 0\n            ecb += eb_l[kk];\n            if (ecb > t) {\n                ecb = t;\n            }\n#else\n            ecb = t;\n#endif\n            ++k, ++kk;\n        }\n        dd = (1 + 2 * dd) / (2 * dd_n);\n        avg_mask = tab[dd] * 0.5f;\n        ecb *= avg_mask;\n\n        /****   long block pre-echo control   ****/\n        /* dont use long block pre-echo control if previous granule was \n         * a short block.  This is to avoid the situation:   \n         * frame0:  quiet (very low masking)  \n         * frame1:  surge  (triggers short blocks)\n         * frame2:  regular frame.  looks like pre-echo when compared to \n         *          frame0, but all pre-echo was in frame1.\n         */\n        /* chn=0,1   L and R channels\n           chn=2,3   S and M channels.\n         */\n        if (psv->blocktype_old[chn & 0x01] == SHORT_TYPE) {\n            FLOAT const ecb_limit = rpelev * psv->nb_l1[chn][b];\n            if (ecb_limit > 0) {\n                thr[b] = Min(ecb, ecb_limit);\n            }\n            else {\n                /* Robert 071209:\n                   Because we don't calculate long block psy when we know a granule\n                   should be of short blocks, we don't have any clue how the granule\n                   before would have looked like as a long block. So we have to guess\n                   a little bit for this END_TYPE block.\n                   Most of the time we get away with this sloppyness. (fingers crossed :)\n                   The speed increase is worth it.\n                 */\n                thr[b] = Min(ecb, eb_l[b] * NS_PREECHO_ATT2);\n            }\n        }\n        else {\n            FLOAT   ecb_limit_2 = rpelev2 * psv->nb_l2[chn][b];\n            FLOAT   ecb_limit_1 = rpelev * psv->nb_l1[chn][b];\n            FLOAT   ecb_limit;\n            if (ecb_limit_2 <= 0) {\n                ecb_limit_2 = ecb;\n            }\n            if (ecb_limit_1 <= 0) {\n                ecb_limit_1 = ecb;\n            }\n            if (psv->blocktype_old[chn & 0x01] == NORM_TYPE) {\n                ecb_limit = Min(ecb_limit_1, ecb_limit_2);\n            }\n            else {\n                ecb_limit = ecb_limit_1;\n            }\n            thr[b] = Min(ecb, ecb_limit);\n        }\n        psv->nb_l2[chn][b] = psv->nb_l1[chn][b];\n        psv->nb_l1[chn][b] = ecb;\n        {\n            /*  if THR exceeds EB, the quantization routines will take the difference\n             *  from other bands. in case of strong tonal samples (tonaltest.wav)\n             *  this leads to heavy distortions. that's why we limit THR here.\n             */\n            x = max[b];\n            x *= gdl->minval[b];\n            x *= avg_mask;\n            if (thr[b] > x) {\n                thr[b] = x;\n            }\n        }\n        if (masking_lower > 1) {\n            thr[b] *= masking_lower;\n        }\n        if (thr[b] > eb_l[b]) {\n            thr[b] = eb_l[b];\n        }\n        if (masking_lower < 1) {\n            thr[b] *= masking_lower;\n        }\n        assert(thr[b] >= 0);\n    }\n    for (; b < CBANDS; ++b) {\n        eb_l[b] = 0;\n        thr[b] = 0;\n    }\n}\n\n\nstatic void\nvbrpsy_compute_block_type(SessionConfig_t const *cfg, int *uselongblock)\n{\n    int     chn;\n\n    if (cfg->short_blocks == short_block_coupled\n        /* force both channels to use the same block type */\n        /* this is necessary if the frame is to be encoded in ms_stereo.  */\n        /* But even without ms_stereo, FhG  does this */\n        && !(uselongblock[0] && uselongblock[1]))\n        uselongblock[0] = uselongblock[1] = 0;\n\n    for (chn = 0; chn < cfg->channels_out; chn++) {\n        /* disable short blocks */\n        if (cfg->short_blocks == short_block_dispensed) {\n            uselongblock[chn] = 1;\n        }\n        if (cfg->short_blocks == short_block_forced) {\n            uselongblock[chn] = 0;\n        }\n    }\n}\n\n\nstatic void\nvbrpsy_apply_block_type(PsyStateVar_t * psv, int nch, int const *uselongblock, int *blocktype_d)\n{\n    int     chn;\n\n    /* update the blocktype of the previous granule, since it depends on what\n     * happend in this granule */\n    for (chn = 0; chn < nch; chn++) {\n        int     blocktype = NORM_TYPE;\n        /* disable short blocks */\n\n        if (uselongblock[chn]) {\n            /* no attack : use long blocks */\n            assert(psv->blocktype_old[chn] != START_TYPE);\n            if (psv->blocktype_old[chn] == SHORT_TYPE)\n                blocktype = STOP_TYPE;\n        }\n        else {\n            /* attack : use short blocks */\n            blocktype = SHORT_TYPE;\n            if (psv->blocktype_old[chn] == NORM_TYPE) {\n                psv->blocktype_old[chn] = START_TYPE;\n            }\n            if (psv->blocktype_old[chn] == STOP_TYPE)\n                psv->blocktype_old[chn] = SHORT_TYPE;\n        }\n\n        blocktype_d[chn] = psv->blocktype_old[chn]; /* value returned to calling program */\n        psv->blocktype_old[chn] = blocktype; /* save for next call to l3psy_anal */\n    }\n}\n\n\n/*************************************************************** \n * compute M/S thresholds from Johnston & Ferreira 1992 ICASSP paper\n ***************************************************************/\n\nstatic void\nvbrpsy_compute_MS_thresholds(const FLOAT eb[4][CBANDS], FLOAT thr[4][CBANDS],\n                             const FLOAT cb_mld[CBANDS], const FLOAT ath_cb[CBANDS], FLOAT athlower,\n                             FLOAT msfix, int n)\n{\n    FLOAT const msfix2 = msfix * 2.f;\n    FLOAT   rside, rmid;\n    int     b;\n    for (b = 0; b < n; ++b) {\n        FLOAT const ebM = eb[2][b];\n        FLOAT const ebS = eb[3][b];\n        FLOAT const thmL = thr[0][b];\n        FLOAT const thmR = thr[1][b];\n        FLOAT   thmM = thr[2][b];\n        FLOAT   thmS = thr[3][b];\n\n        /* use this fix if L & R masking differs by 2db or less */\n        /* if db = 10*log10(x2/x1) < 2 */\n        /* if (x2 < 1.58*x1) { */\n        if (thmL <= 1.58f * thmR && thmR <= 1.58f * thmL) {\n            FLOAT const mld_m = cb_mld[b] * ebS;\n            FLOAT const mld_s = cb_mld[b] * ebM;\n            FLOAT const tmp_m = Min(thmS, mld_m);\n            FLOAT const tmp_s = Min(thmM, mld_s);\n            rmid = Max(thmM, tmp_m);\n            rside = Max(thmS, tmp_s);\n        }\n        else {\n            rmid = thmM;\n            rside = thmS;\n        }\n        if (msfix > 0.f) {\n            /***************************************************************/\n            /* Adjust M/S maskings if user set \"msfix\"                     */\n            /***************************************************************/\n            /* Naoki Shibata 2000 */\n            FLOAT   thmLR, thmMS;\n            FLOAT const ath = ath_cb[b] * athlower;\n            FLOAT const tmp_l = Max(thmL, ath);\n            FLOAT const tmp_r = Max(thmR, ath);\n            thmLR = Min(tmp_l, tmp_r);\n            thmM = Max(rmid, ath);\n            thmS = Max(rside, ath);\n            thmMS = thmM + thmS;\n            if (thmMS > 0.f && (thmLR * msfix2) < thmMS) {\n                FLOAT const f = thmLR * msfix2 / thmMS;\n                thmM *= f;\n                thmS *= f;\n                assert(thmMS > 0.f);\n            }\n            rmid = Min(thmM, rmid);\n            rside = Min(thmS, rside);\n        }\n        if (rmid > ebM) {\n            rmid = ebM;\n        }\n        if (rside > ebS) {\n            rside = ebS;\n        }\n        thr[2][b] = rmid;\n        thr[3][b] = rside;\n    }\n}\n\n\n/*\n * NOTE: the bitrate reduction from the inter-channel masking effect is low\n * compared to the chance of getting annyoing artefacts. L3psycho_anal_vbr does\n * not use this feature. (Robert 071216)\n*/\n\nint\nL3psycho_anal_vbr(lame_internal_flags * gfc,\n                  const sample_t * const buffer[2], int gr_out,\n                  III_psy_ratio masking_ratio[2][2],\n                  III_psy_ratio masking_MS_ratio[2][2],\n                  FLOAT percep_entropy[2], FLOAT percep_MS_entropy[2],\n                  FLOAT energy[4], int blocktype_d[2])\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    PsyStateVar_t *const psv = &gfc->sv_psy;\n    PsyConst_CB2SB_t const *const gdl = &gfc->cd_psy->l;\n    PsyConst_CB2SB_t const *const gds = &gfc->cd_psy->s;\n    plotting_data *plt = cfg->analysis ? gfc->pinfo : 0;\n\n    III_psy_xmin last_thm[4];\n\n    /* fft and energy calculation   */\n    FLOAT(*wsamp_l)[BLKSIZE];\n    FLOAT(*wsamp_s)[3][BLKSIZE_s];\n    FLOAT   fftenergy[HBLKSIZE];\n    FLOAT   fftenergy_s[3][HBLKSIZE_s];\n    FLOAT   wsamp_L[2][BLKSIZE];\n    FLOAT   wsamp_S[2][3][BLKSIZE_s];\n    FLOAT   eb[4][CBANDS], thr[4][CBANDS];\n\n    FLOAT   sub_short_factor[4][3];\n    FLOAT   thmm;\n    FLOAT const pcfact = 0.6f;\n    FLOAT const ath_factor =\n        (cfg->msfix > 0.f) ? (cfg->ATH_offset_factor * gfc->ATH->adjust_factor) : 1.f;\n\n    const   FLOAT(*const_eb)[CBANDS] = (const FLOAT(*)[CBANDS]) eb;\n    const   FLOAT(*const_fftenergy_s)[HBLKSIZE_s] = (const FLOAT(*)[HBLKSIZE_s]) fftenergy_s;\n\n    /* block type  */\n    int     ns_attacks[4][4] = { {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} };\n    int     uselongblock[2];\n\n    /* usual variables like loop indices, etc..    */\n    int     chn, sb, sblock;\n\n    /* chn=2 and 3 = Mid and Side channels */\n    int const n_chn_psy = (cfg->mode == JOINT_STEREO) ? 4 : cfg->channels_out;\n\n    memcpy(&last_thm[0], &psv->thm[0], sizeof(last_thm));\n\n    vbrpsy_attack_detection(gfc, buffer, gr_out, masking_ratio, masking_MS_ratio, energy,\n                            sub_short_factor, ns_attacks, uselongblock);\n\n    vbrpsy_compute_block_type(cfg, uselongblock);\n\n    /* LONG BLOCK CASE */\n    {\n        for (chn = 0; chn < n_chn_psy; chn++) {\n            int const ch01 = chn & 0x01;\n\n            wsamp_l = wsamp_L + ch01;\n            vbrpsy_compute_fft_l(gfc, buffer, chn, gr_out, fftenergy, wsamp_l);\n            vbrpsy_compute_loudness_approximation_l(gfc, gr_out, chn, fftenergy);\n            vbrpsy_compute_masking_l(gfc, fftenergy, eb[chn], thr[chn], chn);\n        }\n        if (cfg->mode == JOINT_STEREO) {\n            if ((uselongblock[0] + uselongblock[1]) == 2) {\n                vbrpsy_compute_MS_thresholds(const_eb, thr, gdl->mld_cb, gfc->ATH->cb_l,\n                                             ath_factor, cfg->msfix, gdl->npart);\n            }\n        }\n        /* TODO: apply adaptive ATH masking here ?? */\n        for (chn = 0; chn < n_chn_psy; chn++) {\n            convert_partition2scalefac_l(gfc, eb[chn], thr[chn], chn);\n            convert_partition2scalefac_l_to_s(gfc, eb[chn], thr[chn], chn);\n        }\n    }\n    /* SHORT BLOCKS CASE */\n    {\n        int const force_short_block_calc = gfc->cd_psy->force_short_block_calc;\n        for (sblock = 0; sblock < 3; sblock++) {\n            for (chn = 0; chn < n_chn_psy; ++chn) {\n                int const ch01 = chn & 0x01;\n                if (uselongblock[ch01] && !force_short_block_calc) {\n                    vbrpsy_skip_masking_s(gfc, chn, sblock);\n                }\n                else {\n                    /* compute masking thresholds for short blocks */\n                    wsamp_s = wsamp_S + ch01;\n                    vbrpsy_compute_fft_s(gfc, buffer, chn, sblock, fftenergy_s, wsamp_s);\n                    vbrpsy_compute_masking_s(gfc, const_fftenergy_s, eb[chn], thr[chn], chn,\n                                             sblock);\n                }\n            }\n            if (cfg->mode == JOINT_STEREO) {\n                if ((uselongblock[0] + uselongblock[1]) == 0) {\n                    vbrpsy_compute_MS_thresholds(const_eb, thr, gds->mld_cb, gfc->ATH->cb_s,\n                                                 ath_factor, cfg->msfix, gds->npart);\n                }\n            }\n            /* TODO: apply adaptive ATH masking here ?? */\n            for (chn = 0; chn < n_chn_psy; ++chn) {\n                int const ch01 = chn & 0x01;\n                if (!uselongblock[ch01] || force_short_block_calc) {\n                    convert_partition2scalefac_s(gfc, eb[chn], thr[chn], chn, sblock);\n                }\n            }\n        }\n\n        /****   short block pre-echo control   ****/\n        for (chn = 0; chn < n_chn_psy; chn++) {\n            for (sb = 0; sb < SBMAX_s; sb++) {\n                FLOAT   new_thmm[3], prev_thm, t1, t2;\n                for (sblock = 0; sblock < 3; sblock++) {\n                    thmm = psv->thm[chn].s[sb][sblock];\n                    thmm *= NS_PREECHO_ATT0;\n\n                    t1 = t2 = thmm;\n\n                    if (sblock > 0) {\n                        prev_thm = new_thmm[sblock - 1];\n                    }\n                    else {\n                        prev_thm = last_thm[chn].s[sb][2];\n                    }\n                    if (ns_attacks[chn][sblock] >= 2 || ns_attacks[chn][sblock + 1] == 1) {\n                        t1 = NS_INTERP(prev_thm, thmm, NS_PREECHO_ATT1 * pcfact);\n                    }\n                    thmm = Min(t1, thmm);\n                    if (ns_attacks[chn][sblock] == 1) {\n                        t2 = NS_INTERP(prev_thm, thmm, NS_PREECHO_ATT2 * pcfact);\n                    }\n                    else if ((sblock == 0 && psv->last_attacks[chn] == 3)\n                             || (sblock > 0 && ns_attacks[chn][sblock - 1] == 3)) { /* 2nd preceeding block */\n                        switch (sblock) {\n                        case 0:\n                            prev_thm = last_thm[chn].s[sb][1];\n                            break;\n                        case 1:\n                            prev_thm = last_thm[chn].s[sb][2];\n                            break;\n                        case 2:\n                            prev_thm = new_thmm[0];\n                            break;\n                        }\n                        t2 = NS_INTERP(prev_thm, thmm, NS_PREECHO_ATT2 * pcfact);\n                    }\n\n                    thmm = Min(t1, thmm);\n                    thmm = Min(t2, thmm);\n\n                    /* pulse like signal detection for fatboy.wav and so on */\n                    thmm *= sub_short_factor[chn][sblock];\n\n                    new_thmm[sblock] = thmm;\n                }\n                for (sblock = 0; sblock < 3; sblock++) {\n                    psv->thm[chn].s[sb][sblock] = new_thmm[sblock];\n                }\n            }\n        }\n    }\n    for (chn = 0; chn < n_chn_psy; chn++) {\n        psv->last_attacks[chn] = ns_attacks[chn][2];\n    }\n\n\n    /*************************************************************** \n    * determine final block type\n    ***************************************************************/\n    vbrpsy_apply_block_type(psv, cfg->channels_out, uselongblock, blocktype_d);\n\n    /*********************************************************************\n    * compute the value of PE to return ... no delay and advance\n    *********************************************************************/\n    for (chn = 0; chn < n_chn_psy; chn++) {\n        FLOAT  *ppe;\n        int     type;\n        III_psy_ratio const *mr;\n\n        if (chn > 1) {\n            ppe = percep_MS_entropy - 2;\n            type = NORM_TYPE;\n            if (blocktype_d[0] == SHORT_TYPE || blocktype_d[1] == SHORT_TYPE)\n                type = SHORT_TYPE;\n            mr = &masking_MS_ratio[gr_out][chn - 2];\n        }\n        else {\n            ppe = percep_entropy;\n            type = blocktype_d[chn];\n            mr = &masking_ratio[gr_out][chn];\n        }\n        if (type == SHORT_TYPE) {\n            ppe[chn] = pecalc_s(mr, gfc->sv_qnt.masking_lower);\n        }\n        else {\n            ppe[chn] = pecalc_l(mr, gfc->sv_qnt.masking_lower);\n        }\n\n        if (plt) {\n            plt->pe[gr_out][chn] = ppe[chn];\n        }\n    }\n    return 0;\n}\n\n\n\n\n/* \n *   The spreading function.  Values returned in units of energy\n */\nstatic  FLOAT\ns3_func(FLOAT bark)\n{\n    FLOAT   tempx, x, tempy, temp;\n    tempx = bark;\n    if (tempx >= 0)\n        tempx *= 3;\n    else\n        tempx *= 1.5;\n\n    if (tempx >= 0.5 && tempx <= 2.5) {\n        temp = tempx - 0.5;\n        x = 8.0 * (temp * temp - 2.0 * temp);\n    }\n    else\n        x = 0.0;\n    tempx += 0.474;\n    tempy = 15.811389 + 7.5 * tempx - 17.5 * sqrt(1.0 + tempx * tempx);\n\n    if (tempy <= -60.0)\n        return 0.0;\n\n    tempx = exp((x + tempy) * LN_TO_LOG10);\n\n    /* Normalization.  The spreading function should be normalized so that:\n       +inf\n       /\n       |  s3 [ bark ]  d(bark)   =  1\n       /\n       -inf\n     */\n    tempx /= .6609193;\n    return tempx;\n}\n\n#if 0\nstatic  FLOAT\nnorm_s3_func(void)\n{\n    double  lim_a = 0, lim_b = 0;\n    double  x = 0, l, h;\n    for (x = 0; s3_func(x) > 1e-20; x -= 1);\n    l = x;\n    h = 0;\n    while (fabs(h - l) > 1e-12) {\n        x = (h + l) / 2;\n        if (s3_func(x) > 0) {\n            h = x;\n        }\n        else {\n            l = x;\n        }\n    }\n    lim_a = l;\n    for (x = 0; s3_func(x) > 1e-20; x += 1);\n    l = 0;\n    h = x;\n    while (fabs(h - l) > 1e-12) {\n        x = (h + l) / 2;\n        if (s3_func(x) > 0) {\n            l = x;\n        }\n        else {\n            h = x;\n        }\n    }\n    lim_b = h;\n    {\n        double  sum = 0;\n        int const m = 1000;\n        int     i;\n        for (i = 0; i <= m; ++i) {\n            double  x = lim_a + i * (lim_b - lim_a) / m;\n            double  y = s3_func(x);\n            sum += y;\n        }\n        {\n            double  norm = (m + 1) / (sum * (lim_b - lim_a));\n            /*printf( \"norm = %lf\\n\",norm); */\n            return norm;\n        }\n    }\n}\n#endif\n\nstatic  FLOAT\nstereo_demask(double f)\n{\n    /* setup stereo demasking thresholds */\n    /* formula reverse enginerred from plot in paper */\n    double  arg = freq2bark(f);\n    arg = (Min(arg, 15.5) / 15.5);\n\n    return pow(10.0, 1.25 * (1 - cos(PI * arg)) - 2.5);\n}\n\nstatic void\ninit_numline(PsyConst_CB2SB_t * gd, FLOAT sfreq, int fft_size,\n             int mdct_size, int sbmax, int const *scalepos)\n{\n    FLOAT   b_frq[CBANDS + 1];\n    FLOAT const mdct_freq_frac = sfreq / (2.0f * mdct_size);\n    FLOAT const deltafreq = fft_size / (2.0f * mdct_size);\n    int     partition[HBLKSIZE] = { 0 };\n    int     i, j, ni;\n    int     sfb;\n    sfreq /= fft_size;\n    j = 0;\n    ni = 0;\n    /* compute numlines, the number of spectral lines in each partition band */\n    /* each partition band should be about DELBARK wide. */\n    for (i = 0; i < CBANDS; i++) {\n        FLOAT   bark1;\n        int     j2, nl;\n        bark1 = freq2bark(sfreq * j);\n\n        b_frq[i] = sfreq * j;\n\n        for (j2 = j; freq2bark(sfreq * j2) - bark1 < DELBARK && j2 <= fft_size / 2; j2++);\n\n        nl = j2 - j;\n        gd->numlines[i] = nl;\n        gd->rnumlines[i] = (nl > 0) ? (1.0f / nl) : 0;\n\n        ni = i + 1;\n\n        while (j < j2) {\n            assert(j < HBLKSIZE);\n            partition[j++] = i;\n        }\n        if (j > fft_size / 2) {\n            j = fft_size / 2;\n            ++i;\n            break;\n        }\n    }\n    assert(i < CBANDS);\n    b_frq[i] = sfreq * j;\n\n    gd->n_sb = sbmax;\n    gd->npart = ni;\n\n    {\n        j = 0;\n        for (i = 0; i < gd->npart; i++) {\n            int const nl = gd->numlines[i];\n            FLOAT const freq = sfreq * (j + nl / 2);\n            gd->mld_cb[i] = stereo_demask(freq);\n            j += nl;\n        }\n        for (; i < CBANDS; ++i) {\n            gd->mld_cb[i] = 1;\n        }\n    }\n    for (sfb = 0; sfb < sbmax; sfb++) {\n        int     i1, i2, bo;\n        int     start = scalepos[sfb];\n        int     end = scalepos[sfb + 1];\n\n        i1 = floor(.5 + deltafreq * (start - .5));\n        if (i1 < 0)\n            i1 = 0;\n        i2 = floor(.5 + deltafreq * (end - .5));\n\n        if (i2 > fft_size / 2)\n            i2 = fft_size / 2;\n\n        bo = partition[i2];\n        gd->bm[sfb] = (partition[i1] + partition[i2]) / 2;\n        gd->bo[sfb] = bo;\n\n        /* calculate how much of this band belongs to current scalefactor band */\n        {\n            FLOAT const f_tmp = mdct_freq_frac * end;\n            FLOAT   bo_w = (f_tmp - b_frq[bo]) / (b_frq[bo + 1] - b_frq[bo]);\n            if (bo_w < 0) {\n                bo_w = 0;\n            }\n            else {\n                if (bo_w > 1) {\n                    bo_w = 1;\n                }\n            }\n            gd->bo_weight[sfb] = bo_w;\n        }\n        gd->mld[sfb] = stereo_demask(mdct_freq_frac * start);\n    }\n}\n\nstatic void\ncompute_bark_values(PsyConst_CB2SB_t const *gd, FLOAT sfreq, int fft_size,\n                    FLOAT * bval, FLOAT * bval_width)\n{\n    /* compute bark values of each critical band */\n    int     k, j = 0, ni = gd->npart;\n    sfreq /= fft_size;\n    for (k = 0; k < ni; k++) {\n        int const w = gd->numlines[k];\n        FLOAT   bark1, bark2;\n\n        bark1 = freq2bark(sfreq * (j));\n        bark2 = freq2bark(sfreq * (j + w - 1));\n        bval[k] = .5 * (bark1 + bark2);\n\n        bark1 = freq2bark(sfreq * (j - .5));\n        bark2 = freq2bark(sfreq * (j + w - .5));\n        bval_width[k] = bark2 - bark1;\n        j += w;\n    }\n}\n\nstatic int\ninit_s3_values(FLOAT ** p, int (*s3ind)[2], int npart,\n               FLOAT const *bval, FLOAT const *bval_width, FLOAT const *norm)\n{\n    FLOAT   s3[CBANDS][CBANDS];\n    /* The s3 array is not linear in the bark scale.\n     * bval[x] should be used to get the bark value.\n     */\n    int     i, j, k;\n    int     numberOfNoneZero = 0;\n\n    memset(&s3[0][0], 0, sizeof(s3));\n\n    /* s[i][j], the value of the spreading function,\n     * centered at band j (masker), for band i (maskee)\n     *\n     * i.e.: sum over j to spread into signal barkval=i\n     * NOTE: i and j are used opposite as in the ISO docs\n     */\n    for (i = 0; i < npart; i++) {\n        for (j = 0; j < npart; j++) {\n            FLOAT   v = s3_func(bval[i] - bval[j]) * bval_width[j];\n            s3[i][j] = v * norm[i];\n        }\n    }\n    for (i = 0; i < npart; i++) {\n        for (j = 0; j < npart; j++) {\n            if (s3[i][j] > 0.0f)\n                break;\n        }\n        s3ind[i][0] = j;\n\n        for (j = npart - 1; j > 0; j--) {\n            if (s3[i][j] > 0.0f)\n                break;\n        }\n        s3ind[i][1] = j;\n        numberOfNoneZero += (s3ind[i][1] - s3ind[i][0] + 1);\n    }\n    *p = malloc(sizeof(FLOAT) * numberOfNoneZero);\n    if (!*p)\n        return -1;\n\n    k = 0;\n    for (i = 0; i < npart; i++)\n        for (j = s3ind[i][0]; j <= s3ind[i][1]; j++)\n            (*p)[k++] = s3[i][j];\n\n    return 0;\n}\n\nint\npsymodel_init(lame_global_flags const *gfp)\n{\n    lame_internal_flags *const gfc = gfp->internal_flags;\n    SessionConfig_t *const cfg = &gfc->cfg;\n    PsyStateVar_t *const psv = &gfc->sv_psy;\n    PsyConst_t *gd;\n    int     i, j, b, sb, k;\n    FLOAT   bvl_a = 13, bvl_b = 24;\n    FLOAT   snr_l_a = 0, snr_l_b = 0;\n    FLOAT   snr_s_a = -8.25, snr_s_b = -4.5;\n\n    FLOAT   bval[CBANDS];\n    FLOAT   bval_width[CBANDS];\n    FLOAT   norm[CBANDS];\n    FLOAT const sfreq = cfg->samplerate_out;\n\n    FLOAT   xav = 10, xbv = 12;\n    FLOAT const minval_low = (0.f - cfg->minval);\n\n    if (gfc->cd_psy != 0) {\n        return 0;\n    }\n    memset(norm, 0, sizeof(norm));\n\n    gd = calloc(1, sizeof(PsyConst_t));\n    gfc->cd_psy = gd;\n\n    gd->force_short_block_calc = gfp->experimentalZ;\n\n    psv->blocktype_old[0] = psv->blocktype_old[1] = NORM_TYPE; /* the vbr header is long blocks */\n\n    for (i = 0; i < 4; ++i) {\n        for (j = 0; j < CBANDS; ++j) {\n            psv->nb_l1[i][j] = 1e20;\n            psv->nb_l2[i][j] = 1e20;\n            psv->nb_s1[i][j] = psv->nb_s2[i][j] = 1.0;\n        }\n        for (sb = 0; sb < SBMAX_l; sb++) {\n            psv->en[i].l[sb] = 1e20;\n            psv->thm[i].l[sb] = 1e20;\n        }\n        for (j = 0; j < 3; ++j) {\n            for (sb = 0; sb < SBMAX_s; sb++) {\n                psv->en[i].s[sb][j] = 1e20;\n                psv->thm[i].s[sb][j] = 1e20;\n            }\n            psv->last_attacks[i] = 0;\n        }\n        for (j = 0; j < 9; j++)\n            psv->last_en_subshort[i][j] = 10.;\n    }\n\n\n    /* init. for loudness approx. -jd 2001 mar 27 */\n    psv->loudness_sq_save[0] = psv->loudness_sq_save[1] = 0.0;\n\n\n\n    /*************************************************************************\n     * now compute the psychoacoustic model specific constants\n     ************************************************************************/\n    /* compute numlines, bo, bm, bval, bval_width, mld */\n    init_numline(&gd->l, sfreq, BLKSIZE, 576, SBMAX_l, gfc->scalefac_band.l);\n    assert(gd->l.npart < CBANDS);\n    compute_bark_values(&gd->l, sfreq, BLKSIZE, bval, bval_width);\n\n    /* compute the spreading function */\n    for (i = 0; i < gd->l.npart; i++) {\n        double  snr = snr_l_a;\n        if (bval[i] >= bvl_a) {\n            snr = snr_l_b * (bval[i] - bvl_a) / (bvl_b - bvl_a)\n                + snr_l_a * (bvl_b - bval[i]) / (bvl_b - bvl_a);\n        }\n        norm[i] = pow(10.0, snr / 10.0);\n    }\n    i = init_s3_values(&gd->l.s3, gd->l.s3ind, gd->l.npart, bval, bval_width, norm);\n    if (i)\n        return i;\n\n    /* compute long block specific values, ATH and MINVAL */\n    j = 0;\n    for (i = 0; i < gd->l.npart; i++) {\n        double  x;\n\n        /* ATH */\n        x = FLOAT_MAX;\n        for (k = 0; k < gd->l.numlines[i]; k++, j++) {\n            FLOAT const freq = sfreq * j / (1000.0 * BLKSIZE);\n            FLOAT   level;\n            /* freq = Min(.1,freq); *//* ATH below 100 Hz constant, not further climbing */\n            level = ATHformula(cfg, freq * 1000) - 20; /* scale to FFT units; returned value is in dB */\n            level = pow(10., 0.1 * level); /* convert from dB -> energy */\n            level *= gd->l.numlines[i];\n            if (x > level)\n                x = level;\n        }\n        gfc->ATH->cb_l[i] = x;\n\n        /* MINVAL.\n           For low freq, the strength of the masking is limited by minval\n           this is an ISO MPEG1 thing, dont know if it is really needed */\n        /* FIXME: it does work to reduce low-freq problems in S53-Wind-Sax\n           and lead-voice samples, but introduces some 3 kbps bit bloat too.\n           TODO: Further refinement of the shape of this hack.\n         */\n        x = 20.0 * (bval[i] / xav - 1.0);\n        if (x > 6) {\n            x = 30;\n        }\n        if (x < minval_low) {\n            x = minval_low;\n        }\n        if (cfg->samplerate_out < 44000) {\n            x = 30;\n        }\n        x -= 8.;\n        gd->l.minval[i] = pow(10.0, x / 10.) * gd->l.numlines[i];\n    }\n\n    /************************************************************************\n     * do the same things for short blocks\n     ************************************************************************/\n    init_numline(&gd->s, sfreq, BLKSIZE_s, 192, SBMAX_s, gfc->scalefac_band.s);\n    assert(gd->s.npart < CBANDS);\n    compute_bark_values(&gd->s, sfreq, BLKSIZE_s, bval, bval_width);\n\n    /* SNR formula. short block is normalized by SNR. is it still right ? */\n    j = 0;\n    for (i = 0; i < gd->s.npart; i++) {\n        double  x;\n        double  snr = snr_s_a;\n        if (bval[i] >= bvl_a) {\n            snr = snr_s_b * (bval[i] - bvl_a) / (bvl_b - bvl_a)\n                + snr_s_a * (bvl_b - bval[i]) / (bvl_b - bvl_a);\n        }\n        norm[i] = pow(10.0, snr / 10.0);\n\n        /* ATH */\n        x = FLOAT_MAX;\n        for (k = 0; k < gd->s.numlines[i]; k++, j++) {\n            FLOAT const freq = sfreq * j / (1000.0 * BLKSIZE_s);\n            FLOAT   level;\n            /* freq = Min(.1,freq); *//* ATH below 100 Hz constant, not further climbing */\n            level = ATHformula(cfg, freq * 1000) - 20; /* scale to FFT units; returned value is in dB */\n            level = pow(10., 0.1 * level); /* convert from dB -> energy */\n            level *= gd->s.numlines[i];\n            if (x > level)\n                x = level;\n        }\n        gfc->ATH->cb_s[i] = x;\n\n        /* MINVAL.\n           For low freq, the strength of the masking is limited by minval\n           this is an ISO MPEG1 thing, dont know if it is really needed */\n        x = 7.0 * (bval[i] / xbv - 1.0);\n        if (bval[i] > xbv) {\n            x *= 1 + log(1 + x) * 3.1;\n        }\n        if (bval[i] < xbv) {\n            x *= 1 + log(1 - x) * 2.3;\n        }\n        if (x > 6) {\n            x = 30;\n        }\n        if (x < minval_low) {\n            x = minval_low;\n        }\n        if (cfg->samplerate_out < 44000) {\n            x = 30;\n        }\n        x -= 8;\n        gd->s.minval[i] = pow(10.0, x / 10) * gd->s.numlines[i];\n    }\n\n    i = init_s3_values(&gd->s.s3, gd->s.s3ind, gd->s.npart, bval, bval_width, norm);\n    if (i)\n        return i;\n\n\n    init_mask_add_max_values();\n    init_fft(gfc);\n\n    /* setup temporal masking */\n    gd->decay = exp(-1.0 * LOG10 / (temporalmask_sustain_sec * sfreq / 192.0));\n\n    {\n        FLOAT   msfix;\n        msfix = NS_MSFIX;\n        if (cfg->use_safe_joint_stereo)\n            msfix = 1.0;\n        if (fabs(cfg->msfix) > 0.0)\n            msfix = cfg->msfix;\n        cfg->msfix = msfix;\n\n        /* spread only from npart_l bands.  Normally, we use the spreading\n         * function to convolve from npart_l down to npart_l bands \n         */\n        for (b = 0; b < gd->l.npart; b++)\n            if (gd->l.s3ind[b][1] > gd->l.npart - 1)\n                gd->l.s3ind[b][1] = gd->l.npart - 1;\n    }\n\n    /*  prepare for ATH auto adjustment:\n     *  we want to decrease the ATH by 12 dB per second\n     */\n#define  frame_duration (576. * cfg->mode_gr / sfreq)\n    gfc->ATH->decay = pow(10., -12. / 10. * frame_duration);\n    gfc->ATH->adjust_factor = 0.01; /* minimum, for leading low loudness */\n    gfc->ATH->adjust_limit = 1.0; /* on lead, allow adjust up to maximum */\n#undef  frame_duration\n\n    assert(gd->l.bo[SBMAX_l - 1] <= gd->l.npart);\n    assert(gd->s.bo[SBMAX_s - 1] <= gd->s.npart);\n\n    if (cfg->ATHtype != -1) {\n        /* compute equal loudness weights (eql_w) */\n        FLOAT   freq;\n        FLOAT const freq_inc = (FLOAT) cfg->samplerate_out / (FLOAT) (BLKSIZE);\n        FLOAT   eql_balance = 0.0;\n        freq = 0.0;\n        for (i = 0; i < BLKSIZE / 2; ++i) {\n            /* convert ATH dB to relative power (not dB) */\n            /*  to determine eql_w */\n            freq += freq_inc;\n            gfc->ATH->eql_w[i] = 1. / pow(10, ATHformula(cfg, freq) / 10);\n            eql_balance += gfc->ATH->eql_w[i];\n        }\n        eql_balance = 1.0 / eql_balance;\n        for (i = BLKSIZE / 2; --i >= 0;) { /* scale weights */\n            gfc->ATH->eql_w[i] *= eql_balance;\n        }\n    }\n    {\n        for (b = j = 0; b < gd->s.npart; ++b) {\n            for (i = 0; i < gd->s.numlines[b]; ++i) {\n                ++j;\n            }\n        }\n        assert(j == 129);\n        for (b = j = 0; b < gd->l.npart; ++b) {\n            for (i = 0; i < gd->l.numlines[b]; ++i) {\n                ++j;\n            }\n        }\n        assert(j == 513);\n    }\n    /* short block attack threshold */\n    {\n        float   x = gfp->attackthre;\n        float   y = gfp->attackthre_s;\n        if (x < 0) {\n            x = NSATTACKTHRE;\n        }\n        if (y < 0) {\n            y = NSATTACKTHRE_S;\n        }\n        gd->attack_threshold[0] = gd->attack_threshold[1] = gd->attack_threshold[2] = x;\n        gd->attack_threshold[3] = y;\n    }\n    {\n        float   sk_s = -10.f, sk_l = -4.7f;\n        static float const sk[] =\n            { -7.4, -7.4, -7.4, -9.5, -7.4, -6.1, -5.5, -4.7, -4.7, -4.7, -4.7 };\n        if (gfp->VBR_q < 4) {\n            sk_l = sk_s = sk[0];\n        }\n        else {\n            sk_l = sk_s = sk[gfp->VBR_q] + gfp->VBR_q_frac * (sk[gfp->VBR_q] - sk[gfp->VBR_q + 1]);\n        }\n        b = 0;\n        for (; b < gd->s.npart; b++) {\n            float   m = (float) (gd->s.npart - b) / gd->s.npart;\n            gd->s.masking_lower[b] = powf(10.f, sk_s * m * 0.1f);\n        }\n        for (; b < CBANDS; ++b) {\n            gd->s.masking_lower[b] = 1.f;\n        }\n        b = 0;\n        for (; b < gd->l.npart; b++) {\n            float   m = (float) (gd->l.npart - b) / gd->l.npart;\n            gd->l.masking_lower[b] = powf(10.f, sk_l * m * 0.1f);\n        }\n        for (; b < CBANDS; ++b) {\n            gd->l.masking_lower[b] = 1.f;\n        }\n    }\n    memcpy(&gd->l_to_s, &gd->l, sizeof(gd->l_to_s));\n    init_numline(&gd->l_to_s, sfreq, BLKSIZE, 192, SBMAX_s, gfc->scalefac_band.s);\n    return 0;\n}\n"
  },
  {
    "path": "app/jni/libmp3lame/psymodel.h",
    "content": "/*\n *\tpsymodel.h\n *\n *\tCopyright (c) 1999 Mark Taylor\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_PSYMODEL_H\n#define LAME_PSYMODEL_H\n\n\nint     L3psycho_anal_ns(lame_internal_flags * gfc,\n                         const sample_t *const buffer[2], int gr,\n                         III_psy_ratio ratio[2][2],\n                         III_psy_ratio MS_ratio[2][2],\n                         FLOAT pe[2], FLOAT pe_MS[2], FLOAT ener[2], int blocktype_d[2]);\n\nint     L3psycho_anal_vbr(lame_internal_flags * gfc,\n                          const sample_t *const buffer[2], int gr,\n                          III_psy_ratio ratio[2][2],\n                          III_psy_ratio MS_ratio[2][2],\n                          FLOAT pe[2], FLOAT pe_MS[2], FLOAT ener[2], int blocktype_d[2]);\n\n\nint     psymodel_init(lame_global_flags const* gfp);\n\n\n#define rpelev 2\n#define rpelev2 16\n#define rpelev_s 2\n#define rpelev2_s 16\n\n/* size of each partition band, in barks: */\n#define DELBARK .34\n\n\n/* tuned for output level (sensitive to energy scale) */\n#define VO_SCALE (1./( 14752*14752 )/(BLKSIZE/2))\n\n#define temporalmask_sustain_sec 0.01\n\n#define NS_PREECHO_ATT0 0.8\n#define NS_PREECHO_ATT1 0.6\n#define NS_PREECHO_ATT2 0.3\n\n#define NS_MSFIX 3.5\n#define NSATTACKTHRE 4.4\n#define NSATTACKTHRE_S 25\n\n#endif /* LAME_PSYMODEL_H */\n"
  },
  {
    "path": "app/jni/libmp3lame/quantize.c",
    "content": "/*\n * MP3 quantization\n *\n *      Copyright (c) 1999-2000 Mark Taylor\n *      Copyright (c) 1999-2003 Takehiro Tominaga\n *      Copyright (c) 2000-2011 Robert Hegemann\n *      Copyright (c) 2001-2005 Gabriel Bouvigne\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: quantize.c,v 1.216.2.1 2012/01/08 23:49:58 robert Exp $ */\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include <string.h>\n#include <strings.h>\n#include <stdlib.h>\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"quantize_pvt.h\"\n#include \"reservoir.h\"\n#include \"bitstream.h\"\n#include \"vbrquantize.h\"\n#include \"quantize.h\"\n#ifdef HAVE_XMMINTRIN_H\n#include \"vector/lame_intrin.h\"\n#endif\n\n\n\n\n/* convert from L/R <-> Mid/Side */\nstatic void\nms_convert(III_side_info_t * l3_side, int gr)\n{\n    int     i;\n    for (i = 0; i < 576; ++i) {\n        FLOAT   l, r;\n        l = l3_side->tt[gr][0].xr[i];\n        r = l3_side->tt[gr][1].xr[i];\n        l3_side->tt[gr][0].xr[i] = (l + r) * (FLOAT) (SQRT2 * 0.5);\n        l3_side->tt[gr][1].xr[i] = (l - r) * (FLOAT) (SQRT2 * 0.5);\n    }\n}\n\n/************************************************************************\n *\n *      init_outer_loop()\n *  mt 6/99\n *\n *  initializes cod_info, scalefac and xrpow\n *\n *  returns 0 if all energies in xr are zero, else 1\n *\n ************************************************************************/\n\nstatic void\ninit_xrpow_core_c(gr_info * const cod_info, FLOAT xrpow[576], int upper, FLOAT * sum)\n{\n    int     i;\n    FLOAT   tmp;\n    *sum = 0;\n    for (i = 0; i <= upper; ++i) {\n        tmp = fabs(cod_info->xr[i]);\n        *sum += tmp;\n        xrpow[i] = sqrt(tmp * sqrt(tmp));\n\n        if (xrpow[i] > cod_info->xrpow_max)\n            cod_info->xrpow_max = xrpow[i];\n    }\n}\n\n\n\n\n\nvoid\ninit_xrpow_core_init(lame_internal_flags * const gfc)\n{\n    gfc->init_xrpow_core = init_xrpow_core_c;\n\n#if defined(HAVE_XMMINTRIN_H)\n    if (gfc->CPU_features.SSE)\n        gfc->init_xrpow_core = init_xrpow_core_sse;\n#endif\n#ifndef HAVE_NASM\n#ifdef MIN_ARCH_SSE\n    gfc->init_xrpow_core = init_xrpow_core_sse;\n#endif\n#endif\n}\n\n\n\nstatic int\ninit_xrpow(lame_internal_flags * gfc, gr_info * const cod_info, FLOAT xrpow[576])\n{\n    FLOAT   sum = 0;\n    int     i;\n    int const upper = cod_info->max_nonzero_coeff;\n\n    assert(xrpow != NULL);\n    cod_info->xrpow_max = 0;\n\n    /*  check if there is some energy we have to quantize\n     *  and calculate xrpow matching our fresh scalefactors\n     */\n    assert(0 <= upper && upper <= 575);\n    memset(&(xrpow[upper]), 0, (576 - upper) * sizeof(xrpow[0]));\n\n\n    gfc->init_xrpow_core(cod_info, xrpow, upper, &sum);\n\n    /*  return 1 if we have something to quantize, else 0\n     */\n    if (sum > (FLOAT) 1E-20) {\n        int     j = 0;\n        if (gfc->sv_qnt.substep_shaping & 2)\n            j = 1;\n\n        for (i = 0; i < cod_info->psymax; i++)\n            gfc->sv_qnt.pseudohalf[i] = j;\n\n        return 1;\n    }\n\n    memset(&cod_info->l3_enc[0], 0, sizeof(int) * 576);\n    return 0;\n}\n\n\n\n\n\n/*\nGabriel Bouvigne feb/apr 2003\nAnalog silence detection in partitionned sfb21\nor sfb12 for short blocks\n\nFrom top to bottom of sfb, changes to 0\ncoeffs which are below ath. It stops on the first\ncoeff higher than ath.\n*/\nstatic void\npsfb21_analogsilence(lame_internal_flags const *gfc, gr_info * const cod_info)\n{\n    ATH_t const *const ATH = gfc->ATH;\n    FLOAT  *const xr = cod_info->xr;\n\n    if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type, but not SHORT blocks */\n        int     gsfb;\n        int     stop = 0;\n        for (gsfb = PSFB21 - 1; gsfb >= 0 && !stop; gsfb--) {\n            int const start = gfc->scalefac_band.psfb21[gsfb];\n            int const end = gfc->scalefac_band.psfb21[gsfb + 1];\n            int     j;\n            FLOAT   ath21;\n            ath21 = athAdjust(ATH->adjust_factor, ATH->psfb21[gsfb], ATH->floor, 0);\n\n            if (gfc->sv_qnt.longfact[21] > 1e-12f)\n                ath21 *= gfc->sv_qnt.longfact[21];\n\n            for (j = end - 1; j >= start; j--) {\n                if (fabs(xr[j]) < ath21)\n                    xr[j] = 0;\n                else {\n                    stop = 1;\n                    break;\n                }\n            }\n        }\n    }\n    else {\n        /*note: short blocks coeffs are reordered */\n        int     block;\n        for (block = 0; block < 3; block++) {\n\n            int     gsfb;\n            int     stop = 0;\n            for (gsfb = PSFB12 - 1; gsfb >= 0 && !stop; gsfb--) {\n                int const start = gfc->scalefac_band.s[12] * 3 +\n                    (gfc->scalefac_band.s[13] - gfc->scalefac_band.s[12]) * block +\n                    (gfc->scalefac_band.psfb12[gsfb] - gfc->scalefac_band.psfb12[0]);\n                int const end =\n                    start + (gfc->scalefac_band.psfb12[gsfb + 1] - gfc->scalefac_band.psfb12[gsfb]);\n                int     j;\n                FLOAT   ath12;\n                ath12 = athAdjust(ATH->adjust_factor, ATH->psfb12[gsfb], ATH->floor, 0);\n\n                if (gfc->sv_qnt.shortfact[12] > 1e-12f)\n                    ath12 *= gfc->sv_qnt.shortfact[12];\n\n                for (j = end - 1; j >= start; j--) {\n                    if (fabs(xr[j]) < ath12)\n                        xr[j] = 0;\n                    else {\n                        stop = 1;\n                        break;\n                    }\n                }\n            }\n        }\n    }\n\n}\n\n\n\n\n\nstatic void\ninit_outer_loop(lame_internal_flags const *gfc, gr_info * const cod_info)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     sfb, j;\n    /*  initialize fresh cod_info\n     */\n    cod_info->part2_3_length = 0;\n    cod_info->big_values = 0;\n    cod_info->count1 = 0;\n    cod_info->global_gain = 210;\n    cod_info->scalefac_compress = 0;\n    /* mixed_block_flag, block_type was set in psymodel.c */\n    cod_info->table_select[0] = 0;\n    cod_info->table_select[1] = 0;\n    cod_info->table_select[2] = 0;\n    cod_info->subblock_gain[0] = 0;\n    cod_info->subblock_gain[1] = 0;\n    cod_info->subblock_gain[2] = 0;\n    cod_info->subblock_gain[3] = 0; /* this one is always 0 */\n    cod_info->region0_count = 0;\n    cod_info->region1_count = 0;\n    cod_info->preflag = 0;\n    cod_info->scalefac_scale = 0;\n    cod_info->count1table_select = 0;\n    cod_info->part2_length = 0;\n    if (cfg->samplerate_out <= 8000) {\n      cod_info->sfb_lmax = 17;\n      cod_info->sfb_smin = 9;\n      cod_info->psy_lmax = 17;\n    }\n    else {\n      cod_info->sfb_lmax = SBPSY_l;\n      cod_info->sfb_smin = SBPSY_s;\n      cod_info->psy_lmax = gfc->sv_qnt.sfb21_extra ? SBMAX_l : SBPSY_l;\n    }\n    cod_info->psymax = cod_info->psy_lmax;\n    cod_info->sfbmax = cod_info->sfb_lmax;\n    cod_info->sfbdivide = 11;\n    for (sfb = 0; sfb < SBMAX_l; sfb++) {\n        cod_info->width[sfb]\n            = gfc->scalefac_band.l[sfb + 1] - gfc->scalefac_band.l[sfb];\n        cod_info->window[sfb] = 3; /* which is always 0. */\n    }\n    if (cod_info->block_type == SHORT_TYPE) {\n        FLOAT   ixwork[576];\n        FLOAT  *ix;\n\n        cod_info->sfb_smin = 0;\n        cod_info->sfb_lmax = 0;\n        if (cod_info->mixed_block_flag) {\n            /*\n             *  MPEG-1:      sfbs 0-7 long block, 3-12 short blocks\n             *  MPEG-2(.5):  sfbs 0-5 long block, 3-12 short blocks\n             */\n            cod_info->sfb_smin = 3;\n            cod_info->sfb_lmax = cfg->mode_gr * 2 + 4;\n        }\n        if (cfg->samplerate_out <= 8000) {\n            cod_info->psymax\n                = cod_info->sfb_lmax\n                + 3 * (9 - cod_info->sfb_smin);\n            cod_info->sfbmax = cod_info->sfb_lmax + 3 * (9 - cod_info->sfb_smin);\n        }\n        else {\n            cod_info->psymax\n                = cod_info->sfb_lmax\n                + 3 * ((gfc->sv_qnt.sfb21_extra ? SBMAX_s : SBPSY_s) - cod_info->sfb_smin);\n            cod_info->sfbmax = cod_info->sfb_lmax + 3 * (SBPSY_s - cod_info->sfb_smin);\n        }\n        cod_info->sfbdivide = cod_info->sfbmax - 18;\n        cod_info->psy_lmax = cod_info->sfb_lmax;\n        /* re-order the short blocks, for more efficient encoding below */\n        /* By Takehiro TOMINAGA */\n        /*\n           Within each scalefactor band, data is given for successive\n           time windows, beginning with window 0 and ending with window 2.\n           Within each window, the quantized values are then arranged in\n           order of increasing frequency...\n         */\n        ix = &cod_info->xr[gfc->scalefac_band.l[cod_info->sfb_lmax]];\n        memcpy(ixwork, cod_info->xr, 576 * sizeof(FLOAT));\n        for (sfb = cod_info->sfb_smin; sfb < SBMAX_s; sfb++) {\n            int const start = gfc->scalefac_band.s[sfb];\n            int const end = gfc->scalefac_band.s[sfb + 1];\n            int     window, l;\n            for (window = 0; window < 3; window++) {\n                for (l = start; l < end; l++) {\n                    *ix++ = ixwork[3 * l + window];\n                }\n            }\n        }\n\n        j = cod_info->sfb_lmax;\n        for (sfb = cod_info->sfb_smin; sfb < SBMAX_s; sfb++) {\n            cod_info->width[j] = cod_info->width[j + 1] = cod_info->width[j + 2]\n                = gfc->scalefac_band.s[sfb + 1] - gfc->scalefac_band.s[sfb];\n            cod_info->window[j] = 0;\n            cod_info->window[j + 1] = 1;\n            cod_info->window[j + 2] = 2;\n            j += 3;\n        }\n    }\n\n    cod_info->count1bits = 0;\n    cod_info->sfb_partition_table = nr_of_sfb_block[0][0];\n    cod_info->slen[0] = 0;\n    cod_info->slen[1] = 0;\n    cod_info->slen[2] = 0;\n    cod_info->slen[3] = 0;\n\n    cod_info->max_nonzero_coeff = 575;\n\n    /*  fresh scalefactors are all zero\n     */\n    memset(cod_info->scalefac, 0, sizeof(cod_info->scalefac));\n\n    if (cfg->vbr != vbr_mt && cfg->vbr != vbr_mtrh && cfg->vbr != vbr_abr && cfg->vbr != vbr_off) {\n        psfb21_analogsilence(gfc, cod_info);\n    }\n}\n\n\n\n/************************************************************************\n *\n *      bin_search_StepSize()\n *\n *  author/date??\n *\n *  binary step size search\n *  used by outer_loop to get a quantizer step size to start with\n *\n ************************************************************************/\n\ntypedef enum {\n    BINSEARCH_NONE,\n    BINSEARCH_UP,\n    BINSEARCH_DOWN\n} binsearchDirection_t;\n\nstatic int\nbin_search_StepSize(lame_internal_flags * const gfc, gr_info * const cod_info,\n                    int desired_rate, const int ch, const FLOAT xrpow[576])\n{\n    int     nBits;\n    int     CurrentStep = gfc->sv_qnt.CurrentStep[ch];\n    int     flag_GoneOver = 0;\n    int const start = gfc->sv_qnt.OldValue[ch];\n    binsearchDirection_t Direction = BINSEARCH_NONE;\n    cod_info->global_gain = start;\n    desired_rate -= cod_info->part2_length;\n\n    assert(CurrentStep);\n    for (;;) {\n        int     step;\n        nBits = count_bits(gfc, xrpow, cod_info, 0);\n\n        if (CurrentStep == 1 || nBits == desired_rate)\n            break;      /* nothing to adjust anymore */\n\n        if (nBits > desired_rate) {\n            /* increase Quantize_StepSize */\n            if (Direction == BINSEARCH_DOWN)\n                flag_GoneOver = 1;\n\n            if (flag_GoneOver)\n                CurrentStep /= 2;\n            Direction = BINSEARCH_UP;\n            step = CurrentStep;\n        }\n        else {\n            /* decrease Quantize_StepSize */\n            if (Direction == BINSEARCH_UP)\n                flag_GoneOver = 1;\n\n            if (flag_GoneOver)\n                CurrentStep /= 2;\n            Direction = BINSEARCH_DOWN;\n            step = -CurrentStep;\n        }\n        cod_info->global_gain += step;\n        if (cod_info->global_gain < 0) {\n            cod_info->global_gain = 0;\n            flag_GoneOver = 1;\n        }\n        if (cod_info->global_gain > 255) {\n            cod_info->global_gain = 255;\n            flag_GoneOver = 1;\n        }\n    }\n\n    assert(cod_info->global_gain >= 0);\n    assert(cod_info->global_gain < 256);\n\n    while (nBits > desired_rate && cod_info->global_gain < 255) {\n        cod_info->global_gain++;\n        nBits = count_bits(gfc, xrpow, cod_info, 0);\n    }\n    gfc->sv_qnt.CurrentStep[ch] = (start - cod_info->global_gain >= 4) ? 4 : 2;\n    gfc->sv_qnt.OldValue[ch] = cod_info->global_gain;\n    cod_info->part2_3_length = nBits;\n    return nBits;\n}\n\n\n\n\n/************************************************************************\n *\n *      trancate_smallspectrums()\n *\n *  Takehiro TOMINAGA 2002-07-21\n *\n *  trancate smaller nubmers into 0 as long as the noise threshold is allowed.\n *\n ************************************************************************/\nstatic int\nfloatcompare(const void *v1, const void *v2)\n{\n    const FLOAT *const a = v1, *const b = v2;\n    if (*a > *b)\n        return 1;\n    if (*a < *b)\n        return -1;\n    return 0;\n}\n\nstatic void\ntrancate_smallspectrums(lame_internal_flags const *gfc,\n                        gr_info * const gi, const FLOAT * const l3_xmin, FLOAT * const work)\n{\n    int     sfb, j, width;\n    FLOAT   distort[SFBMAX];\n    calc_noise_result dummy;\n\n    if ((!(gfc->sv_qnt.substep_shaping & 4) && gi->block_type == SHORT_TYPE)\n        || gfc->sv_qnt.substep_shaping & 0x80)\n        return;\n    (void) calc_noise(gi, l3_xmin, distort, &dummy, 0);\n    for (j = 0; j < 576; j++) {\n        FLOAT   xr = 0.0;\n        if (gi->l3_enc[j] != 0)\n            xr = fabs(gi->xr[j]);\n        work[j] = xr;\n    }\n\n    j = 0;\n    sfb = 8;\n    if (gi->block_type == SHORT_TYPE)\n        sfb = 6;\n    do {\n        FLOAT   allowedNoise, trancateThreshold;\n        int     nsame, start;\n\n        width = gi->width[sfb];\n        j += width;\n        if (distort[sfb] >= 1.0)\n            continue;\n\n        qsort(&work[j - width], width, sizeof(FLOAT), floatcompare);\n        if (EQ(work[j - 1], 0.0))\n            continue;   /* all zero sfb */\n\n        allowedNoise = (1.0 - distort[sfb]) * l3_xmin[sfb];\n        trancateThreshold = 0.0;\n        start = 0;\n        do {\n            FLOAT   noise;\n            for (nsame = 1; start + nsame < width; nsame++)\n                if (NEQ(work[start + j - width], work[start + j + nsame - width]))\n                    break;\n\n            noise = work[start + j - width] * work[start + j - width] * nsame;\n            if (allowedNoise < noise) {\n                if (start != 0)\n                    trancateThreshold = work[start + j - width - 1];\n                break;\n            }\n            allowedNoise -= noise;\n            start += nsame;\n        } while (start < width);\n        if (EQ(trancateThreshold, 0.0))\n            continue;\n\n/*      printf(\"%e %e %e\\n\", */\n/*             trancateThreshold/l3_xmin[sfb], */\n/*             trancateThreshold/(l3_xmin[sfb]*start), */\n/*             trancateThreshold/(l3_xmin[sfb]*(start+width)) */\n/*          ); */\n/*      if (trancateThreshold > 1000*l3_xmin[sfb]*start) */\n/*          trancateThreshold = 1000*l3_xmin[sfb]*start; */\n\n        do {\n            if (fabs(gi->xr[j - width]) <= trancateThreshold)\n                gi->l3_enc[j - width] = 0;\n        } while (--width > 0);\n    } while (++sfb < gi->psymax);\n\n    gi->part2_3_length = noquant_count_bits(gfc, gi, 0);\n}\n\n\n/*************************************************************************\n *\n *      loop_break()\n *\n *  author/date??\n *\n *  Function: Returns zero if there is a scalefac which has not been\n *            amplified. Otherwise it returns one.\n *\n *************************************************************************/\n\ninline static int\nloop_break(const gr_info * const cod_info)\n{\n    int     sfb;\n\n    for (sfb = 0; sfb < cod_info->sfbmax; sfb++)\n        if (cod_info->scalefac[sfb]\n            + cod_info->subblock_gain[cod_info->window[sfb]] == 0)\n            return 0;\n\n    return 1;\n}\n\n\n\n\n/*  mt 5/99:  Function: Improved calc_noise for a single channel   */\n\n/*************************************************************************\n *\n *      quant_compare()\n *\n *  author/date??\n *\n *  several different codes to decide which quantization is better\n *\n *************************************************************************/\n\nstatic double\npenalties(double noise)\n{\n    return FAST_LOG10(0.368 + 0.632 * noise * noise * noise);\n}\n\nstatic double\nget_klemm_noise(const FLOAT * distort, const gr_info * const gi)\n{\n    int     sfb;\n    double  klemm_noise = 1E-37;\n    for (sfb = 0; sfb < gi->psymax; sfb++)\n        klemm_noise += penalties(distort[sfb]);\n\n    return Max(1e-20, klemm_noise);\n}\n\ninline static int\nquant_compare(const int quant_comp,\n              const calc_noise_result * const best,\n              calc_noise_result * const calc, const gr_info * const gi, const FLOAT * distort)\n{\n    /*\n       noise is given in decibels (dB) relative to masking thesholds.\n\n       over_noise:  ??? (the previous comment is fully wrong)\n       tot_noise:   ??? (the previous comment is fully wrong)\n       max_noise:   max quantization noise\n\n     */\n    int     better;\n\n    switch (quant_comp) {\n    default:\n    case 9:{\n            if (best->over_count > 0) {\n                /* there are distorted sfb */\n                better = calc->over_SSD <= best->over_SSD;\n                if (calc->over_SSD == best->over_SSD)\n                    better = calc->bits < best->bits;\n            }\n            else {\n                /* no distorted sfb */\n                better = ((calc->max_noise < 0) &&\n                          ((calc->max_noise * 10 + calc->bits) <=\n                           (best->max_noise * 10 + best->bits)));\n            }\n            break;\n        }\n\n    case 0:\n        better = calc->over_count < best->over_count\n            || (calc->over_count == best->over_count && calc->over_noise < best->over_noise)\n            || (calc->over_count == best->over_count &&\n                EQ(calc->over_noise, best->over_noise) && calc->tot_noise < best->tot_noise);\n        break;\n\n    case 8:\n        calc->max_noise = get_klemm_noise(distort, gi);\n        /*lint --fallthrough */\n    case 1:\n        better = calc->max_noise < best->max_noise;\n        break;\n    case 2:\n        better = calc->tot_noise < best->tot_noise;\n        break;\n    case 3:\n        better = (calc->tot_noise < best->tot_noise)\n            && (calc->max_noise < best->max_noise);\n        break;\n    case 4:\n        better = (calc->max_noise <= 0.0 && best->max_noise > 0.2)\n            || (calc->max_noise <= 0.0 &&\n                best->max_noise < 0.0 &&\n                best->max_noise > calc->max_noise - 0.2 && calc->tot_noise < best->tot_noise)\n            || (calc->max_noise <= 0.0 &&\n                best->max_noise > 0.0 &&\n                best->max_noise > calc->max_noise - 0.2 &&\n                calc->tot_noise < best->tot_noise + best->over_noise)\n            || (calc->max_noise > 0.0 &&\n                best->max_noise > -0.05 &&\n                best->max_noise > calc->max_noise - 0.1 &&\n                calc->tot_noise + calc->over_noise < best->tot_noise + best->over_noise)\n            || (calc->max_noise > 0.0 &&\n                best->max_noise > -0.1 &&\n                best->max_noise > calc->max_noise - 0.15 &&\n                calc->tot_noise + calc->over_noise + calc->over_noise <\n                best->tot_noise + best->over_noise + best->over_noise);\n        break;\n    case 5:\n        better = calc->over_noise < best->over_noise\n            || (EQ(calc->over_noise, best->over_noise) && calc->tot_noise < best->tot_noise);\n        break;\n    case 6:\n        better = calc->over_noise < best->over_noise\n            || (EQ(calc->over_noise, best->over_noise) &&\n                (calc->max_noise < best->max_noise\n                 || (EQ(calc->max_noise, best->max_noise) && calc->tot_noise <= best->tot_noise)\n                ));\n        break;\n    case 7:\n        better = calc->over_count < best->over_count || calc->over_noise < best->over_noise;\n        break;\n    }\n\n\n    if (best->over_count == 0) {\n        /*\n           If no distorted bands, only use this quantization\n           if it is better, and if it uses less bits.\n           Unfortunately, part2_3_length is sometimes a poor\n           estimator of the final size at low bitrates.\n         */\n        better = better && calc->bits < best->bits;\n    }\n\n\n    return better;\n}\n\n\n\n/*************************************************************************\n *\n *          amp_scalefac_bands()\n *\n *  author/date??\n *\n *  Amplify the scalefactor bands that violate the masking threshold.\n *  See ISO 11172-3 Section C.1.5.4.3.5\n *\n *  distort[] = noise/masking\n *  distort[] > 1   ==> noise is not masked\n *  distort[] < 1   ==> noise is masked\n *  max_dist = maximum value of distort[]\n *\n *  Three algorithms:\n *  noise_shaping_amp\n *        0             Amplify all bands with distort[]>1.\n *\n *        1             Amplify all bands with distort[] >= max_dist^(.5);\n *                     ( 50% in the db scale)\n *\n *        2             Amplify first band with distort[] >= max_dist;\n *\n *\n *  For algorithms 0 and 1, if max_dist < 1, then amplify all bands\n *  with distort[] >= .95*max_dist.  This is to make sure we always\n *  amplify at least one band.\n *\n *\n *************************************************************************/\nstatic void\namp_scalefac_bands(lame_internal_flags * gfc,\n                   gr_info * const cod_info, FLOAT const *distort, FLOAT xrpow[576], int bRefine)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     j, sfb;\n    FLOAT   ifqstep34, trigger;\n    int     noise_shaping_amp;\n\n    if (cod_info->scalefac_scale == 0) {\n        ifqstep34 = 1.29683955465100964055; /* 2**(.75*.5) */\n    }\n    else {\n        ifqstep34 = 1.68179283050742922612; /* 2**(.75*1) */\n    }\n\n    /* compute maximum value of distort[]  */\n    trigger = 0;\n    for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {\n        if (trigger < distort[sfb])\n            trigger = distort[sfb];\n    }\n\n    noise_shaping_amp = cfg->noise_shaping_amp;\n    if (noise_shaping_amp == 3) {\n        if (bRefine == 1)\n            noise_shaping_amp = 2;\n        else\n            noise_shaping_amp = 1;\n    }\n    switch (noise_shaping_amp) {\n    case 2:\n        /* amplify exactly 1 band */\n        break;\n\n    case 1:\n        /* amplify bands within 50% of max (on db scale) */\n        if (trigger > 1.0)\n            trigger = pow(trigger, .5);\n        else\n            trigger *= .95;\n        break;\n\n    case 0:\n    default:\n        /* ISO algorithm.  amplify all bands with distort>1 */\n        if (trigger > 1.0)\n            trigger = 1.0;\n        else\n            trigger *= .95;\n        break;\n    }\n\n    j = 0;\n    for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {\n        int const width = cod_info->width[sfb];\n        int     l;\n        j += width;\n        if (distort[sfb] < trigger)\n            continue;\n\n        if (gfc->sv_qnt.substep_shaping & 2) {\n            gfc->sv_qnt.pseudohalf[sfb] = !gfc->sv_qnt.pseudohalf[sfb];\n            if (!gfc->sv_qnt.pseudohalf[sfb] && cfg->noise_shaping_amp == 2)\n                return;\n        }\n        cod_info->scalefac[sfb]++;\n        for (l = -width; l < 0; l++) {\n            xrpow[j + l] *= ifqstep34;\n            if (xrpow[j + l] > cod_info->xrpow_max)\n                cod_info->xrpow_max = xrpow[j + l];\n        }\n\n        if (cfg->noise_shaping_amp == 2)\n            return;\n    }\n}\n\n/*************************************************************************\n *\n *      inc_scalefac_scale()\n *\n *  Takehiro Tominaga 2000-xx-xx\n *\n *  turns on scalefac scale and adjusts scalefactors\n *\n *************************************************************************/\n\nstatic void\ninc_scalefac_scale(gr_info * const cod_info, FLOAT xrpow[576])\n{\n    int     l, j, sfb;\n    const FLOAT ifqstep34 = 1.29683955465100964055;\n\n    j = 0;\n    for (sfb = 0; sfb < cod_info->sfbmax; sfb++) {\n        int const width = cod_info->width[sfb];\n        int     s = cod_info->scalefac[sfb];\n        if (cod_info->preflag)\n            s += pretab[sfb];\n        j += width;\n        if (s & 1) {\n            s++;\n            for (l = -width; l < 0; l++) {\n                xrpow[j + l] *= ifqstep34;\n                if (xrpow[j + l] > cod_info->xrpow_max)\n                    cod_info->xrpow_max = xrpow[j + l];\n            }\n        }\n        cod_info->scalefac[sfb] = s >> 1;\n    }\n    cod_info->preflag = 0;\n    cod_info->scalefac_scale = 1;\n}\n\n\n\n/*************************************************************************\n *\n *      inc_subblock_gain()\n *\n *  Takehiro Tominaga 2000-xx-xx\n *\n *  increases the subblock gain and adjusts scalefactors\n *\n *************************************************************************/\n\nstatic int\ninc_subblock_gain(const lame_internal_flags * const gfc, gr_info * const cod_info, FLOAT xrpow[576])\n{\n    int     sfb, window;\n    int    *const scalefac = cod_info->scalefac;\n\n    /* subbloc_gain can't do anything in the long block region */\n    for (sfb = 0; sfb < cod_info->sfb_lmax; sfb++) {\n        if (scalefac[sfb] >= 16)\n            return 1;\n    }\n\n    for (window = 0; window < 3; window++) {\n        int     s1, s2, l, j;\n        s1 = s2 = 0;\n\n        for (sfb = cod_info->sfb_lmax + window; sfb < cod_info->sfbdivide; sfb += 3) {\n            if (s1 < scalefac[sfb])\n                s1 = scalefac[sfb];\n        }\n        for (; sfb < cod_info->sfbmax; sfb += 3) {\n            if (s2 < scalefac[sfb])\n                s2 = scalefac[sfb];\n        }\n\n        if (s1 < 16 && s2 < 8)\n            continue;\n\n        if (cod_info->subblock_gain[window] >= 7)\n            return 1;\n\n        /* even though there is no scalefactor for sfb12\n         * subblock gain affects upper frequencies too, that's why\n         * we have to go up to SBMAX_s\n         */\n        cod_info->subblock_gain[window]++;\n        j = gfc->scalefac_band.l[cod_info->sfb_lmax];\n        for (sfb = cod_info->sfb_lmax + window; sfb < cod_info->sfbmax; sfb += 3) {\n            FLOAT   amp;\n            int const width = cod_info->width[sfb];\n            int     s = scalefac[sfb];\n            assert(s >= 0);\n            s = s - (4 >> cod_info->scalefac_scale);\n            if (s >= 0) {\n                scalefac[sfb] = s;\n                j += width * 3;\n                continue;\n            }\n\n            scalefac[sfb] = 0;\n            {\n                int const gain = 210 + (s << (cod_info->scalefac_scale + 1));\n                amp = IPOW20(gain);\n            }\n            j += width * (window + 1);\n            for (l = -width; l < 0; l++) {\n                xrpow[j + l] *= amp;\n                if (xrpow[j + l] > cod_info->xrpow_max)\n                    cod_info->xrpow_max = xrpow[j + l];\n            }\n            j += width * (3 - window - 1);\n        }\n\n        {\n            FLOAT const amp = IPOW20(202);\n            j += cod_info->width[sfb] * (window + 1);\n            for (l = -cod_info->width[sfb]; l < 0; l++) {\n                xrpow[j + l] *= amp;\n                if (xrpow[j + l] > cod_info->xrpow_max)\n                    cod_info->xrpow_max = xrpow[j + l];\n            }\n        }\n    }\n    return 0;\n}\n\n\n\n/********************************************************************\n *\n *      balance_noise()\n *\n *  Takehiro Tominaga /date??\n *  Robert Hegemann 2000-09-06: made a function of it\n *\n *  amplifies scalefactor bands,\n *   - if all are already amplified returns 0\n *   - if some bands are amplified too much:\n *      * try to increase scalefac_scale\n *      * if already scalefac_scale was set\n *          try on short blocks to increase subblock gain\n *\n ********************************************************************/\ninline static int\nbalance_noise(lame_internal_flags * gfc,\n              gr_info * const cod_info, FLOAT const *distort, FLOAT xrpow[576], int bRefine)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     status;\n\n    amp_scalefac_bands(gfc, cod_info, distort, xrpow, bRefine);\n\n    /* check to make sure we have not amplified too much\n     * loop_break returns 0 if there is an unamplified scalefac\n     * scale_bitcount returns 0 if no scalefactors are too large\n     */\n\n    status = loop_break(cod_info);\n\n    if (status)\n        return 0;       /* all bands amplified */\n\n    /* not all scalefactors have been amplified.  so these\n     * scalefacs are possibly valid.  encode them:\n     */\n    status = scale_bitcount(gfc, cod_info);\n\n    if (!status)\n        return 1;       /* amplified some bands not exceeding limits */\n\n    /*  some scalefactors are too large.\n     *  lets try setting scalefac_scale=1\n     */\n    if (cfg->noise_shaping > 1) {\n        memset(&gfc->sv_qnt.pseudohalf[0], 0, sizeof(gfc->sv_qnt.pseudohalf));\n        if (!cod_info->scalefac_scale) {\n            inc_scalefac_scale(cod_info, xrpow);\n            status = 0;\n        }\n        else {\n            if (cod_info->block_type == SHORT_TYPE && cfg->subblock_gain > 0) {\n                status = inc_subblock_gain(gfc, cod_info, xrpow)\n                    || loop_break(cod_info);\n            }\n        }\n    }\n\n    if (!status) {\n        status = scale_bitcount(gfc, cod_info);\n    }\n    return !status;\n}\n\n\n\n/************************************************************************\n *\n *  outer_loop ()\n *\n *  Function: The outer iteration loop controls the masking conditions\n *  of all scalefactorbands. It computes the best scalefac and\n *  global gain. This module calls the inner iteration loop\n *\n *  mt 5/99 completely rewritten to allow for bit reservoir control,\n *  mid/side channels with L/R or mid/side masking thresholds,\n *  and chooses best quantization instead of last quantization when\n *  no distortion free quantization can be found.\n *\n *  added VBR support mt 5/99\n *\n *  some code shuffle rh 9/00\n ************************************************************************/\n\nstatic int\nouter_loop(lame_internal_flags * gfc, gr_info * const cod_info, const FLOAT * const l3_xmin, /* allowed distortion */\n           FLOAT xrpow[576], /* coloured magnitudes of spectral */\n           const int ch, const int targ_bits)\n{                       /* maximum allowed bits */\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    gr_info cod_info_w;\n    FLOAT   save_xrpow[576];\n    FLOAT   distort[SFBMAX];\n    calc_noise_result best_noise_info;\n    int     huff_bits;\n    int     better;\n    int     age;\n    calc_noise_data prev_noise;\n    int     best_part2_3_length = 9999999;\n    int     bEndOfSearch = 0;\n    int     bRefine = 0;\n    int     best_ggain_pass1 = 0;\n\n    (void) bin_search_StepSize(gfc, cod_info, targ_bits, ch, xrpow);\n\n    if (!cfg->noise_shaping)\n        /* fast mode, no noise shaping, we are ready */\n        return 100;     /* default noise_info.over_count */\n\n    memset(&prev_noise, 0, sizeof(calc_noise_data));\n\n\n    /* compute the distortion in this quantization */\n    /* coefficients and thresholds both l/r (or both mid/side) */\n    (void) calc_noise(cod_info, l3_xmin, distort, &best_noise_info, &prev_noise);\n    best_noise_info.bits = cod_info->part2_3_length;\n\n    cod_info_w = *cod_info;\n    age = 0;\n    /* if (cfg->vbr == vbr_rh || cfg->vbr == vbr_mtrh) */\n    memcpy(save_xrpow, xrpow, sizeof(FLOAT) * 576);\n\n    while (!bEndOfSearch) {\n        /* BEGIN MAIN LOOP */\n        do {\n            calc_noise_result noise_info;\n            int     search_limit;\n            int     maxggain = 255;\n\n            /* When quantization with no distorted bands is found,\n             * allow up to X new unsuccesful tries in serial. This\n             * gives us more possibilities for different quant_compare modes.\n             * Much more than 3 makes not a big difference, it is only slower.\n             */\n\n            if (gfc->sv_qnt.substep_shaping & 2) {\n                search_limit = 20;\n            }\n            else {\n                search_limit = 3;\n            }\n\n\n\n            /* Check if the last scalefactor band is distorted.\n             * in VBR mode we can't get rid of the distortion, so quit now\n             * and VBR mode will try again with more bits.\n             * (makes a 10% speed increase, the files I tested were\n             * binary identical, 2000/05/20 Robert Hegemann)\n             * distort[] > 1 means noise > allowed noise\n             */\n            if (gfc->sv_qnt.sfb21_extra) {\n                if (distort[cod_info_w.sfbmax] > 1.0)\n                    break;\n                if (cod_info_w.block_type == SHORT_TYPE\n                    && (distort[cod_info_w.sfbmax + 1] > 1.0\n                        || distort[cod_info_w.sfbmax + 2] > 1.0))\n                    break;\n            }\n\n            /* try a new scalefactor conbination on cod_info_w */\n            if (balance_noise(gfc, &cod_info_w, distort, xrpow, bRefine) == 0)\n                break;\n            if (cod_info_w.scalefac_scale)\n                maxggain = 254;\n\n            /* inner_loop starts with the initial quantization step computed above\n             * and slowly increases until the bits < huff_bits.\n             * Thus it is important not to start with too large of an inital\n             * quantization step.  Too small is ok, but inner_loop will take longer\n             */\n            huff_bits = targ_bits - cod_info_w.part2_length;\n            if (huff_bits <= 0)\n                break;\n\n            /*  increase quantizer stepsize until needed bits are below maximum\n             */\n            while ((cod_info_w.part2_3_length\n                    = count_bits(gfc, xrpow, &cod_info_w, &prev_noise)) > huff_bits\n                   && cod_info_w.global_gain <= maxggain)\n                cod_info_w.global_gain++;\n\n            if (cod_info_w.global_gain > maxggain)\n                break;\n\n            if (best_noise_info.over_count == 0) {\n\n                while ((cod_info_w.part2_3_length\n                        = count_bits(gfc, xrpow, &cod_info_w, &prev_noise)) > best_part2_3_length\n                       && cod_info_w.global_gain <= maxggain)\n                    cod_info_w.global_gain++;\n\n                if (cod_info_w.global_gain > maxggain)\n                    break;\n            }\n\n            /* compute the distortion in this quantization */\n            (void) calc_noise(&cod_info_w, l3_xmin, distort, &noise_info, &prev_noise);\n            noise_info.bits = cod_info_w.part2_3_length;\n\n            /* check if this quantization is better\n             * than our saved quantization */\n            if (cod_info->block_type != SHORT_TYPE) /* NORM, START or STOP type */\n                better = cfg->quant_comp;\n            else\n                better = cfg->quant_comp_short;\n\n\n            better = quant_compare(better, &best_noise_info, &noise_info, &cod_info_w, distort);\n\n\n            /* save data so we can restore this quantization later */\n            if (better) {\n                best_part2_3_length = cod_info->part2_3_length;\n                best_noise_info = noise_info;\n                *cod_info = cod_info_w;\n                age = 0;\n                /* save data so we can restore this quantization later */\n                /*if (cfg->vbr == vbr_rh || cfg->vbr == vbr_mtrh) */  {\n                    /* store for later reuse */\n                    memcpy(save_xrpow, xrpow, sizeof(FLOAT) * 576);\n                }\n            }\n            else {\n                /* early stop? */\n                if (cfg->full_outer_loop == 0) {\n                    if (++age > search_limit && best_noise_info.over_count == 0)\n                        break;\n                    if ((cfg->noise_shaping_amp == 3) && bRefine && age > 30)\n                        break;\n                    if ((cfg->noise_shaping_amp == 3) && bRefine &&\n                        (cod_info_w.global_gain - best_ggain_pass1) > 15)\n                        break;\n                }\n            }\n        }\n        while ((cod_info_w.global_gain + cod_info_w.scalefac_scale) < 255);\n\n        if (cfg->noise_shaping_amp == 3) {\n            if (!bRefine) {\n                /* refine search */\n                cod_info_w = *cod_info;\n                memcpy(xrpow, save_xrpow, sizeof(FLOAT) * 576);\n                age = 0;\n                best_ggain_pass1 = cod_info_w.global_gain;\n\n                bRefine = 1;\n            }\n            else {\n                /* search already refined, stop */\n                bEndOfSearch = 1;\n            }\n\n        }\n        else {\n            bEndOfSearch = 1;\n        }\n    }\n\n    assert((cod_info->global_gain + cod_info->scalefac_scale) <= 255);\n    /*  finish up\n     */\n    if (cfg->vbr == vbr_rh || cfg->vbr == vbr_mtrh || cfg->vbr == vbr_mt)\n        /* restore for reuse on next try */\n        memcpy(xrpow, save_xrpow, sizeof(FLOAT) * 576);\n    /*  do the 'substep shaping'\n     */\n    else if (gfc->sv_qnt.substep_shaping & 1)\n        trancate_smallspectrums(gfc, cod_info, l3_xmin, xrpow);\n\n    return best_noise_info.over_count;\n}\n\n\n\n\n\n/************************************************************************\n *\n *      iteration_finish_one()\n *\n *  Robert Hegemann 2000-09-06\n *\n *  update reservoir status after FINAL quantization/bitrate\n *\n ************************************************************************/\n\nstatic void\niteration_finish_one(lame_internal_flags * gfc, int gr, int ch)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    III_side_info_t *const l3_side = &gfc->l3_side;\n    gr_info *const cod_info = &l3_side->tt[gr][ch];\n\n    /*  try some better scalefac storage\n     */\n    best_scalefac_store(gfc, gr, ch, l3_side);\n\n    /*  best huffman_divide may save some bits too\n     */\n    if (cfg->use_best_huffman == 1)\n        best_huffman_divide(gfc, cod_info);\n\n    /*  update reservoir status after FINAL quantization/bitrate\n     */\n    ResvAdjust(gfc, cod_info);\n}\n\n\n\n/*********************************************************************\n *\n *      VBR_encode_granule()\n *\n *  2000-09-04 Robert Hegemann\n *\n *********************************************************************/\n\nstatic void\nVBR_encode_granule(lame_internal_flags * gfc, gr_info * const cod_info, const FLOAT * const l3_xmin, /* allowed distortion of the scalefactor */\n                   FLOAT xrpow[576], /* coloured magnitudes of spectral values */\n                   const int ch, int min_bits, int max_bits)\n{\n    gr_info bst_cod_info;\n    FLOAT   bst_xrpow[576];\n    int const Max_bits = max_bits;\n    int     real_bits = max_bits + 1;\n    int     this_bits = (max_bits + min_bits) / 2;\n    int     dbits, over, found = 0;\n    int const sfb21_extra = gfc->sv_qnt.sfb21_extra;\n\n    assert(Max_bits <= MAX_BITS_PER_CHANNEL);\n    memset(bst_cod_info.l3_enc, 0, sizeof(bst_cod_info.l3_enc));\n\n    /*  search within round about 40 bits of optimal\n     */\n    do {\n        assert(this_bits >= min_bits);\n        assert(this_bits <= max_bits);\n        assert(min_bits <= max_bits);\n\n        if (this_bits > Max_bits - 42)\n            gfc->sv_qnt.sfb21_extra = 0;\n        else\n            gfc->sv_qnt.sfb21_extra = sfb21_extra;\n\n        over = outer_loop(gfc, cod_info, l3_xmin, xrpow, ch, this_bits);\n\n        /*  is quantization as good as we are looking for ?\n         *  in this case: is no scalefactor band distorted?\n         */\n        if (over <= 0) {\n            found = 1;\n            /*  now we know it can be done with \"real_bits\"\n             *  and maybe we can skip some iterations\n             */\n            real_bits = cod_info->part2_3_length;\n\n            /*  store best quantization so far\n             */\n            bst_cod_info = *cod_info;\n            memcpy(bst_xrpow, xrpow, sizeof(FLOAT) * 576);\n\n            /*  try with fewer bits\n             */\n            max_bits = real_bits - 32;\n            dbits = max_bits - min_bits;\n            this_bits = (max_bits + min_bits) / 2;\n        }\n        else {\n            /*  try with more bits\n             */\n            min_bits = this_bits + 32;\n            dbits = max_bits - min_bits;\n            this_bits = (max_bits + min_bits) / 2;\n\n            if (found) {\n                found = 2;\n                /*  start again with best quantization so far\n                 */\n                *cod_info = bst_cod_info;\n                memcpy(xrpow, bst_xrpow, sizeof(FLOAT) * 576);\n            }\n        }\n    } while (dbits > 12);\n\n    gfc->sv_qnt.sfb21_extra = sfb21_extra;\n\n    /*  found=0 => nothing found, use last one\n     *  found=1 => we just found the best and left the loop\n     *  found=2 => we restored a good one and have now l3_enc to restore too\n     */\n    if (found == 2) {\n        memcpy(cod_info->l3_enc, bst_cod_info.l3_enc, sizeof(int) * 576);\n    }\n    assert(cod_info->part2_3_length <= Max_bits);\n\n}\n\n\n\n/************************************************************************\n *\n *      get_framebits()\n *\n *  Robert Hegemann 2000-09-05\n *\n *  calculates\n *  * how many bits are available for analog silent granules\n *  * how many bits to use for the lowest allowed bitrate\n *  * how many bits each bitrate would provide\n *\n ************************************************************************/\n\nstatic void\nget_framebits(lame_internal_flags * gfc, int frameBits[15])\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncResult_t *const eov = &gfc->ov_enc;\n    int     bitsPerFrame, i;\n\n    /*  always use at least this many bits per granule per channel\n     *  unless we detect analog silence, see below\n     */\n    eov->bitrate_index = cfg->vbr_min_bitrate_index;\n    bitsPerFrame = getframebits(gfc);\n\n    /*  bits for analog silence\n     */\n    eov->bitrate_index = 1;\n    bitsPerFrame = getframebits(gfc);\n\n    for (i = 1; i <= cfg->vbr_max_bitrate_index; i++) {\n        eov->bitrate_index = i;\n        frameBits[i] = ResvFrameBegin(gfc, &bitsPerFrame);\n    }\n}\n\n\n\n/*********************************************************************\n *\n *      VBR_prepare()\n *\n *  2000-09-04 Robert Hegemann\n *\n *  * converts LR to MS coding when necessary\n *  * calculates allowed/adjusted quantization noise amounts\n *  * detects analog silent frames\n *\n *  some remarks:\n *  - lower masking depending on Quality setting\n *  - quality control together with adjusted ATH MDCT scaling\n *    on lower quality setting allocate more noise from\n *    ATH masking, and on higher quality setting allocate\n *    less noise from ATH masking.\n *  - experiments show that going more than 2dB over GPSYCHO's\n *    limits ends up in very annoying artefacts\n *\n *********************************************************************/\n\n/* RH: this one needs to be overhauled sometime */\n\nstatic int\nVBR_old_prepare(lame_internal_flags * gfc,\n                const FLOAT pe[2][2], FLOAT const ms_ener_ratio[2],\n                const III_psy_ratio ratio[2][2],\n                FLOAT l3_xmin[2][2][SFBMAX],\n                int frameBits[16], int min_bits[2][2], int max_bits[2][2], int bands[2][2])\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncResult_t *const eov = &gfc->ov_enc;\n\n    FLOAT   masking_lower_db, adjust = 0.0;\n    int     gr, ch;\n    int     analog_silence = 1;\n    int     avg, mxb, bits = 0;\n\n    eov->bitrate_index = cfg->vbr_max_bitrate_index;\n    avg = ResvFrameBegin(gfc, &avg) / cfg->mode_gr;\n\n    get_framebits(gfc, frameBits);\n\n    for (gr = 0; gr < cfg->mode_gr; gr++) {\n        mxb = on_pe(gfc, pe, max_bits[gr], avg, gr, 0);\n        if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {\n            ms_convert(&gfc->l3_side, gr);\n            reduce_side(max_bits[gr], ms_ener_ratio[gr], avg, mxb);\n        }\n        for (ch = 0; ch < cfg->channels_out; ++ch) {\n            gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];\n\n            if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */\n                adjust = 1.28 / (1 + exp(3.5 - pe[gr][ch] / 300.)) - 0.05;\n                masking_lower_db = gfc->sv_qnt.mask_adjust - adjust;\n            }\n            else {\n                adjust = 2.56 / (1 + exp(3.5 - pe[gr][ch] / 300.)) - 0.14;\n                masking_lower_db = gfc->sv_qnt.mask_adjust_short - adjust;\n            }\n            gfc->sv_qnt.masking_lower = pow(10.0, masking_lower_db * 0.1);\n\n            init_outer_loop(gfc, cod_info);\n            bands[gr][ch] = calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin[gr][ch]);\n            if (bands[gr][ch])\n                analog_silence = 0;\n\n            min_bits[gr][ch] = 126;\n\n            bits += max_bits[gr][ch];\n        }\n    }\n    for (gr = 0; gr < cfg->mode_gr; gr++) {\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            if (bits > frameBits[cfg->vbr_max_bitrate_index] && bits > 0) {\n                max_bits[gr][ch] *= frameBits[cfg->vbr_max_bitrate_index];\n                max_bits[gr][ch] /= bits;\n            }\n            if (min_bits[gr][ch] > max_bits[gr][ch])\n                min_bits[gr][ch] = max_bits[gr][ch];\n\n        }               /* for ch */\n    }                   /* for gr */\n\n    return analog_silence;\n}\n\nstatic void\nbitpressure_strategy(lame_internal_flags const *gfc,\n                     FLOAT l3_xmin[2][2][SFBMAX], const int min_bits[2][2], int max_bits[2][2])\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     gr, ch, sfb;\n    for (gr = 0; gr < cfg->mode_gr; gr++) {\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            gr_info const *const gi = &gfc->l3_side.tt[gr][ch];\n            FLOAT  *pxmin = l3_xmin[gr][ch];\n            for (sfb = 0; sfb < gi->psy_lmax; sfb++)\n                *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_l / SBMAX_l;\n\n            if (gi->block_type == SHORT_TYPE) {\n                for (sfb = gi->sfb_smin; sfb < SBMAX_s; sfb++) {\n                    *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;\n                    *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;\n                    *pxmin++ *= 1. + .029 * sfb * sfb / SBMAX_s / SBMAX_s;\n                }\n            }\n            max_bits[gr][ch] = Max(min_bits[gr][ch], 0.9 * max_bits[gr][ch]);\n        }\n    }\n}\n\n/************************************************************************\n *\n *      VBR_iteration_loop()\n *\n *  tries to find out how many bits are needed for each granule and channel\n *  to get an acceptable quantization. An appropriate bitrate will then be\n *  choosed for quantization.  rh 8/99\n *\n *  Robert Hegemann 2000-09-06 rewrite\n *\n ************************************************************************/\n\nvoid\nVBR_old_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],\n                       const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncResult_t *const eov = &gfc->ov_enc;\n    FLOAT   l3_xmin[2][2][SFBMAX];\n\n    FLOAT   xrpow[576];\n    int     bands[2][2];\n    int     frameBits[15];\n    int     used_bits;\n    int     bits;\n    int     min_bits[2][2], max_bits[2][2];\n    int     mean_bits;\n    int     ch, gr, analog_silence;\n    III_side_info_t *const l3_side = &gfc->l3_side;\n\n    analog_silence = VBR_old_prepare(gfc, pe, ms_ener_ratio, ratio,\n                                     l3_xmin, frameBits, min_bits, max_bits, bands);\n\n    /*---------------------------------*/\n    for (;;) {\n\n        /*  quantize granules with lowest possible number of bits\n         */\n\n        used_bits = 0;\n\n        for (gr = 0; gr < cfg->mode_gr; gr++) {\n            for (ch = 0; ch < cfg->channels_out; ch++) {\n                int     ret;\n                gr_info *const cod_info = &l3_side->tt[gr][ch];\n\n                /*  init_outer_loop sets up cod_info, scalefac and xrpow\n                 */\n                ret = init_xrpow(gfc, cod_info, xrpow);\n                if (ret == 0 || max_bits[gr][ch] == 0) {\n                    /*  xr contains no energy\n                     *  l3_enc, our encoding data, will be quantized to zero\n                     */\n                    continue; /* with next channel */\n                }\n\n                VBR_encode_granule(gfc, cod_info, l3_xmin[gr][ch], xrpow,\n                                   ch, min_bits[gr][ch], max_bits[gr][ch]);\n\n                /*  do the 'substep shaping'\n                 */\n                if (gfc->sv_qnt.substep_shaping & 1) {\n                    trancate_smallspectrums(gfc, &l3_side->tt[gr][ch], l3_xmin[gr][ch], xrpow);\n                }\n\n                ret = cod_info->part2_3_length + cod_info->part2_length;\n                used_bits += ret;\n            }           /* for ch */\n        }               /* for gr */\n\n        /*  find lowest bitrate able to hold used bits\n         */\n        if (analog_silence && !cfg->enforce_min_bitrate)\n            /*  we detected analog silence and the user did not specify\n             *  any hard framesize limit, so start with smallest possible frame\n             */\n            eov->bitrate_index = 1;\n        else\n            eov->bitrate_index = cfg->vbr_min_bitrate_index;\n\n        for (; eov->bitrate_index < cfg->vbr_max_bitrate_index; eov->bitrate_index++) {\n            if (used_bits <= frameBits[eov->bitrate_index])\n                break;\n        }\n        bits = ResvFrameBegin(gfc, &mean_bits);\n\n        if (used_bits <= bits)\n            break;\n\n        bitpressure_strategy(gfc, l3_xmin, (const int (*)[2])min_bits, max_bits);\n\n    }                   /* breaks adjusted */\n    /*--------------------------------------*/\n\n    for (gr = 0; gr < cfg->mode_gr; gr++) {\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            iteration_finish_one(gfc, gr, ch);\n        }               /* for ch */\n    }                   /* for gr */\n    ResvFrameEnd(gfc, mean_bits);\n}\n\n\n\nstatic int\nVBR_new_prepare(lame_internal_flags * gfc,\n                const FLOAT pe[2][2], const III_psy_ratio ratio[2][2],\n                FLOAT l3_xmin[2][2][SFBMAX], int frameBits[16], int max_bits[2][2],\n                int* max_resv)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncResult_t *const eov = &gfc->ov_enc;\n\n    int     gr, ch;\n    int     analog_silence = 1;\n    int     avg, bits = 0;\n    int     maximum_framebits;\n\n    if (!cfg->free_format) {\n        eov->bitrate_index = cfg->vbr_max_bitrate_index;\n        (void) ResvFrameBegin(gfc, &avg);\n        *max_resv = gfc->sv_enc.ResvMax;\n\n        get_framebits(gfc, frameBits);\n        maximum_framebits = frameBits[cfg->vbr_max_bitrate_index];\n    }\n    else {\n        eov->bitrate_index = 0;\n        maximum_framebits = ResvFrameBegin(gfc, &avg);\n        frameBits[0] = maximum_framebits;\n        *max_resv = gfc->sv_enc.ResvMax;\n    }\n\n    for (gr = 0; gr < cfg->mode_gr; gr++) {\n        (void) on_pe(gfc, pe, max_bits[gr], avg, gr, 0);\n        if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {\n            ms_convert(&gfc->l3_side, gr);\n        }\n        for (ch = 0; ch < cfg->channels_out; ++ch) {\n            gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];\n\n            gfc->sv_qnt.masking_lower = pow(10.0, gfc->sv_qnt.mask_adjust * 0.1);\n\n            init_outer_loop(gfc, cod_info);\n            if (0 != calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin[gr][ch]))\n                analog_silence = 0;\n\n            bits += max_bits[gr][ch];\n        }\n    }\n    for (gr = 0; gr < cfg->mode_gr; gr++) {\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            if (bits > maximum_framebits && bits > 0) {\n                max_bits[gr][ch] *= maximum_framebits;\n                max_bits[gr][ch] /= bits;\n            }\n\n        }               /* for ch */\n    }                   /* for gr */\n    if (analog_silence) {\n        *max_resv = 0;\n    }\n    return analog_silence;\n}\n\n\n\nvoid\nVBR_new_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],\n                       const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncResult_t *const eov = &gfc->ov_enc;\n    FLOAT   l3_xmin[2][2][SFBMAX];\n\n    FLOAT   xrpow[2][2][576];\n    int     frameBits[15];\n    int     used_bits;\n    int     max_bits[2][2];\n    int     ch, gr, analog_silence, pad;\n    III_side_info_t *const l3_side = &gfc->l3_side;\n\n    const FLOAT (*const_l3_xmin)[2][SFBMAX] = (const FLOAT (*)[2][SFBMAX])l3_xmin;\n    const FLOAT (*const_xrpow)[2][576] = (const FLOAT (*)[2][576])xrpow;\n    const int (*const_max_bits)[2] = (const int (*)[2])max_bits;\n    \n    (void) ms_ener_ratio; /* not used */\n\n    memset(xrpow, 0, sizeof(xrpow));\n\n    analog_silence = VBR_new_prepare(gfc, pe, ratio, l3_xmin, frameBits, max_bits, &pad);\n\n    for (gr = 0; gr < cfg->mode_gr; gr++) {\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            gr_info *const cod_info = &l3_side->tt[gr][ch];\n\n            /*  init_outer_loop sets up cod_info, scalefac and xrpow\n             */\n            if (0 == init_xrpow(gfc, cod_info, xrpow[gr][ch])) {\n                max_bits[gr][ch] = 0; /* silent granule needs no bits */\n            }\n        }               /* for ch */\n    }                   /* for gr */\n\n    /*  quantize granules with lowest possible number of bits\n     */\n\n    used_bits = VBR_encode_frame(gfc, const_xrpow, const_l3_xmin, const_max_bits);\n\n    if (!cfg->free_format) {\n        int     i, j;\n\n        /*  find lowest bitrate able to hold used bits\n         */\n        if (analog_silence && !cfg->enforce_min_bitrate) {\n            /*  we detected analog silence and the user did not specify\n             *  any hard framesize limit, so start with smallest possible frame\n             */\n            i = 1;\n        }\n        else {\n            i = cfg->vbr_min_bitrate_index;\n        }\n\n        for (; i < cfg->vbr_max_bitrate_index; i++) {\n            if (used_bits <= frameBits[i]) \n                break;\n        }\n        if (i > cfg->vbr_max_bitrate_index) {\n            i = cfg->vbr_max_bitrate_index;\n        }\n        if (pad > 0) {\n            for (j = cfg->vbr_max_bitrate_index; j > i; --j) {\n                int const unused = frameBits[j] - used_bits;\n                if (unused <= pad) \n                    break;\n            }\n            eov->bitrate_index = j;\n        }\n        else {\n            eov->bitrate_index = i;\n        }\n    }\n    else {\n#if 0\n        static int mmm = 0;\n        int     fff = getFramesize_kbps(gfc, used_bits);\n        int     hhh = getFramesize_kbps(gfc, MAX_BITS_PER_GRANULE * cfg->mode_gr);\n        if (mmm < fff)\n            mmm = fff;\n        printf(\"demand=%3d kbps  max=%3d kbps   limit=%3d kbps\\n\", fff, mmm, hhh);\n#endif\n        eov->bitrate_index = 0;\n    }\n    if (used_bits <= frameBits[eov->bitrate_index]) {\n        /* update Reservoire status */\n        int     mean_bits, fullframebits;\n        fullframebits = ResvFrameBegin(gfc, &mean_bits);\n        assert(used_bits <= fullframebits);\n        for (gr = 0; gr < cfg->mode_gr; gr++) {\n            for (ch = 0; ch < cfg->channels_out; ch++) {\n                gr_info const *const cod_info = &l3_side->tt[gr][ch];\n                ResvAdjust(gfc, cod_info);\n            }\n        }\n        ResvFrameEnd(gfc, mean_bits);\n    }\n    else {\n        /* SHOULD NOT HAPPEN INTERNAL ERROR\n         */\n        ERRORF(gfc, \"INTERNAL ERROR IN VBR NEW CODE, please send bug report\\n\");\n        exit(-1);\n    }\n}\n\n\n\n\n\n/********************************************************************\n *\n *  calc_target_bits()\n *\n *  calculates target bits for ABR encoding\n *\n *  mt 2000/05/31\n *\n ********************************************************************/\n\nstatic void\ncalc_target_bits(lame_internal_flags * gfc,\n                 const FLOAT pe[2][2],\n                 FLOAT const ms_ener_ratio[2],\n                 int targ_bits[2][2], int *analog_silence_bits, int *max_frame_bits)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncResult_t *const eov = &gfc->ov_enc;\n    III_side_info_t const *const l3_side = &gfc->l3_side;\n    FLOAT   res_factor;\n    int     gr, ch, totbits, mean_bits;\n    int     framesize = 576 * cfg->mode_gr;\n\n    eov->bitrate_index = cfg->vbr_max_bitrate_index;\n    *max_frame_bits = ResvFrameBegin(gfc, &mean_bits);\n\n    eov->bitrate_index = 1;\n    mean_bits = getframebits(gfc) - cfg->sideinfo_len * 8;\n    *analog_silence_bits = mean_bits / (cfg->mode_gr * cfg->channels_out);\n\n    mean_bits = cfg->vbr_avg_bitrate_kbps * framesize * 1000;\n    if (gfc->sv_qnt.substep_shaping & 1)\n        mean_bits *= 1.09;\n    mean_bits /= cfg->samplerate_out;\n    mean_bits -= cfg->sideinfo_len * 8;\n    mean_bits /= (cfg->mode_gr * cfg->channels_out);\n\n    /*\n       res_factor is the percentage of the target bitrate that should\n       be used on average.  the remaining bits are added to the\n       bitreservoir and used for difficult to encode frames.\n\n       Since we are tracking the average bitrate, we should adjust\n       res_factor \"on the fly\", increasing it if the average bitrate\n       is greater than the requested bitrate, and decreasing it\n       otherwise.  Reasonable ranges are from .9 to 1.0\n\n       Until we get the above suggestion working, we use the following\n       tuning:\n       compression ratio    res_factor\n       5.5  (256kbps)         1.0      no need for bitreservoir\n       11   (128kbps)         .93      7% held for reservoir\n\n       with linear interpolation for other values.\n\n     */\n    res_factor = .93 + .07 * (11.0 - cfg->compression_ratio) / (11.0 - 5.5);\n    if (res_factor < .90)\n        res_factor = .90;\n    if (res_factor > 1.00)\n        res_factor = 1.00;\n\n    for (gr = 0; gr < cfg->mode_gr; gr++) {\n        int     sum = 0;\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            targ_bits[gr][ch] = res_factor * mean_bits;\n\n            if (pe[gr][ch] > 700) {\n                int     add_bits = (pe[gr][ch] - 700) / 1.4;\n\n                gr_info const *const cod_info = &l3_side->tt[gr][ch];\n                targ_bits[gr][ch] = res_factor * mean_bits;\n\n                /* short blocks use a little extra, no matter what the pe */\n                if (cod_info->block_type == SHORT_TYPE) {\n                    if (add_bits < mean_bits / 2)\n                        add_bits = mean_bits / 2;\n                }\n                /* at most increase bits by 1.5*average */\n                if (add_bits > mean_bits * 3 / 2)\n                    add_bits = mean_bits * 3 / 2;\n                else if (add_bits < 0)\n                    add_bits = 0;\n\n                targ_bits[gr][ch] += add_bits;\n            }\n            if (targ_bits[gr][ch] > MAX_BITS_PER_CHANNEL) {\n                targ_bits[gr][ch] = MAX_BITS_PER_CHANNEL;\n            }\n            sum += targ_bits[gr][ch];\n        }               /* for ch */\n        if (sum > MAX_BITS_PER_GRANULE) {\n            for (ch = 0; ch < cfg->channels_out; ++ch) {\n                targ_bits[gr][ch] *= MAX_BITS_PER_GRANULE;\n                targ_bits[gr][ch] /= sum;\n            }\n        }\n    }                   /* for gr */\n\n    if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR)\n        for (gr = 0; gr < cfg->mode_gr; gr++) {\n            reduce_side(targ_bits[gr], ms_ener_ratio[gr], mean_bits * cfg->channels_out,\n                        MAX_BITS_PER_GRANULE);\n        }\n\n    /*  sum target bits\n     */\n    totbits = 0;\n    for (gr = 0; gr < cfg->mode_gr; gr++) {\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            if (targ_bits[gr][ch] > MAX_BITS_PER_CHANNEL)\n                targ_bits[gr][ch] = MAX_BITS_PER_CHANNEL;\n            totbits += targ_bits[gr][ch];\n        }\n    }\n\n    /*  repartion target bits if needed\n     */\n    if (totbits > *max_frame_bits && totbits > 0) {\n        for (gr = 0; gr < cfg->mode_gr; gr++) {\n            for (ch = 0; ch < cfg->channels_out; ch++) {\n                targ_bits[gr][ch] *= *max_frame_bits;\n                targ_bits[gr][ch] /= totbits;\n            }\n        }\n    }\n}\n\n\n\n\n\n\n/********************************************************************\n *\n *  ABR_iteration_loop()\n *\n *  encode a frame with a disired average bitrate\n *\n *  mt 2000/05/31\n *\n ********************************************************************/\n\nvoid\nABR_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],\n                   const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncResult_t *const eov = &gfc->ov_enc;\n    FLOAT   l3_xmin[SFBMAX];\n    FLOAT   xrpow[576];\n    int     targ_bits[2][2];\n    int     mean_bits, max_frame_bits;\n    int     ch, gr, ath_over;\n    int     analog_silence_bits;\n    gr_info *cod_info;\n    III_side_info_t *const l3_side = &gfc->l3_side;\n\n    mean_bits = 0;\n\n    calc_target_bits(gfc, pe, ms_ener_ratio, targ_bits, &analog_silence_bits, &max_frame_bits);\n\n    /*  encode granules\n     */\n    for (gr = 0; gr < cfg->mode_gr; gr++) {\n\n        if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {\n            ms_convert(&gfc->l3_side, gr);\n        }\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            FLOAT   adjust, masking_lower_db;\n            cod_info = &l3_side->tt[gr][ch];\n\n            if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */\n                /* adjust = 1.28/(1+exp(3.5-pe[gr][ch]/300.))-0.05; */\n                adjust = 0;\n                masking_lower_db = gfc->sv_qnt.mask_adjust - adjust;\n            }\n            else {\n                /* adjust = 2.56/(1+exp(3.5-pe[gr][ch]/300.))-0.14; */\n                adjust = 0;\n                masking_lower_db = gfc->sv_qnt.mask_adjust_short - adjust;\n            }\n            gfc->sv_qnt.masking_lower = pow(10.0, masking_lower_db * 0.1);\n\n\n            /*  cod_info, scalefac and xrpow get initialized in init_outer_loop\n             */\n            init_outer_loop(gfc, cod_info);\n            if (init_xrpow(gfc, cod_info, xrpow)) {\n                /*  xr contains energy we will have to encode\n                 *  calculate the masking abilities\n                 *  find some good quantization in outer_loop\n                 */\n                ath_over = calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin);\n                if (0 == ath_over) /* analog silence */\n                    targ_bits[gr][ch] = analog_silence_bits;\n\n                (void) outer_loop(gfc, cod_info, l3_xmin, xrpow, ch, targ_bits[gr][ch]);\n            }\n            iteration_finish_one(gfc, gr, ch);\n        }               /* ch */\n    }                   /* gr */\n\n    /*  find a bitrate which can refill the resevoir to positive size.\n     */\n    for (eov->bitrate_index = cfg->vbr_min_bitrate_index;\n         eov->bitrate_index <= cfg->vbr_max_bitrate_index; eov->bitrate_index++) {\n        if (ResvFrameBegin(gfc, &mean_bits) >= 0)\n            break;\n    }\n    assert(eov->bitrate_index <= cfg->vbr_max_bitrate_index);\n\n    ResvFrameEnd(gfc, mean_bits);\n}\n\n\n\n\n\n\n/************************************************************************\n *\n *      CBR_iteration_loop()\n *\n *  author/date??\n *\n *  encodes one frame of MP3 data with constant bitrate\n *\n ************************************************************************/\n\nvoid\nCBR_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],\n                   const FLOAT ms_ener_ratio[2], const III_psy_ratio ratio[2][2])\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    FLOAT   l3_xmin[SFBMAX];\n    FLOAT   xrpow[576];\n    int     targ_bits[2];\n    int     mean_bits, max_bits;\n    int     gr, ch;\n    III_side_info_t *const l3_side = &gfc->l3_side;\n    gr_info *cod_info;\n\n    (void) ResvFrameBegin(gfc, &mean_bits);\n\n    /* quantize! */\n    for (gr = 0; gr < cfg->mode_gr; gr++) {\n\n        /*  calculate needed bits\n         */\n        max_bits = on_pe(gfc, pe, targ_bits, mean_bits, gr, gr);\n\n        if (gfc->ov_enc.mode_ext == MPG_MD_MS_LR) {\n            ms_convert(&gfc->l3_side, gr);\n            reduce_side(targ_bits, ms_ener_ratio[gr], mean_bits, max_bits);\n        }\n\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            FLOAT   adjust, masking_lower_db;\n            cod_info = &l3_side->tt[gr][ch];\n\n            if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type */\n                /* adjust = 1.28/(1+exp(3.5-pe[gr][ch]/300.))-0.05; */\n                adjust = 0;\n                masking_lower_db = gfc->sv_qnt.mask_adjust - adjust;\n            }\n            else {\n                /* adjust = 2.56/(1+exp(3.5-pe[gr][ch]/300.))-0.14; */\n                adjust = 0;\n                masking_lower_db = gfc->sv_qnt.mask_adjust_short - adjust;\n            }\n            gfc->sv_qnt.masking_lower = pow(10.0, masking_lower_db * 0.1);\n\n            /*  init_outer_loop sets up cod_info, scalefac and xrpow\n             */\n            init_outer_loop(gfc, cod_info);\n            if (init_xrpow(gfc, cod_info, xrpow)) {\n                /*  xr contains energy we will have to encode\n                 *  calculate the masking abilities\n                 *  find some good quantization in outer_loop\n                 */\n                (void) calc_xmin(gfc, &ratio[gr][ch], cod_info, l3_xmin);\n                (void) outer_loop(gfc, cod_info, l3_xmin, xrpow, ch, targ_bits[ch]);\n            }\n\n            iteration_finish_one(gfc, gr, ch);\n            assert(cod_info->part2_3_length <= MAX_BITS_PER_CHANNEL);\n            assert(cod_info->part2_3_length <= targ_bits[ch]);\n        }               /* for ch */\n    }                   /* for gr */\n\n    ResvFrameEnd(gfc, mean_bits);\n}\n"
  },
  {
    "path": "app/jni/libmp3lame/quantize.h",
    "content": "/*\n * MP3 quantization\n *\n * Copyright (c) 1999 Mark Taylor\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_QUANTIZE_H\n#define LAME_QUANTIZE_H\n\nvoid    CBR_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],\n                           const FLOAT ms_ratio[2], const III_psy_ratio ratio[2][2]);\n\nvoid    VBR_old_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],\n                               const FLOAT ms_ratio[2], const III_psy_ratio ratio[2][2]);\n\nvoid    VBR_new_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],\n                               const FLOAT ms_ratio[2], const III_psy_ratio ratio[2][2]);\n\nvoid    ABR_iteration_loop(lame_internal_flags * gfc, const FLOAT pe[2][2],\n                           const FLOAT ms_ratio[2], const III_psy_ratio ratio[2][2]);\n\n\n#endif /* LAME_QUANTIZE_H */\n"
  },
  {
    "path": "app/jni/libmp3lame/quantize_pvt.c",
    "content": "/*\n *      quantize_pvt source file\n *\n *      Copyright (c) 1999-2002 Takehiro Tominaga\n *      Copyright (c) 2000-2012 Robert Hegemann\n *      Copyright (c) 2001 Naoki Shibata\n *      Copyright (c) 2002-2005 Gabriel Bouvigne\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: quantize_pvt.c,v 1.169.2.2 2012/02/07 13:40:37 robert Exp $ */\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"quantize_pvt.h\"\n#include \"reservoir.h\"\n#include \"lame-analysis.h\"\n#include <float.h>\n#include <strings.h>\n\n\n#define NSATHSCALE 100  /* Assuming dynamic range=96dB, this value should be 92 */\n\n/*\n  The following table is used to implement the scalefactor\n  partitioning for MPEG2 as described in section\n  2.4.3.2 of the IS. The indexing corresponds to the\n  way the tables are presented in the IS:\n\n  [table_number][row_in_table][column of nr_of_sfb]\n*/\nconst int nr_of_sfb_block[6][3][4] = {\n    {\n     {6, 5, 5, 5},\n     {9, 9, 9, 9},\n     {6, 9, 9, 9}\n     },\n    {\n     {6, 5, 7, 3},\n     {9, 9, 12, 6},\n     {6, 9, 12, 6}\n     },\n    {\n     {11, 10, 0, 0},\n     {18, 18, 0, 0},\n     {15, 18, 0, 0}\n     },\n    {\n     {7, 7, 7, 0},\n     {12, 12, 12, 0},\n     {6, 15, 12, 0}\n     },\n    {\n     {6, 6, 6, 3},\n     {12, 9, 9, 6},\n     {6, 12, 9, 6}\n     },\n    {\n     {8, 8, 5, 0},\n     {15, 12, 9, 0},\n     {6, 18, 9, 0}\n     }\n};\n\n\n/* Table B.6: layer3 preemphasis */\nconst int pretab[SBMAX_l] = {\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    1, 1, 1, 1, 2, 2, 3, 3, 3, 2, 0\n};\n\n/*\n  Here are MPEG1 Table B.8 and MPEG2 Table B.1\n  -- Layer III scalefactor bands. \n  Index into this using a method such as:\n    idx  = fr_ps->header->sampling_frequency\n           + (fr_ps->header->version * 3)\n*/\n\n\nconst scalefac_struct sfBandIndex[9] = {\n    {                   /* Table B.2.b: 22.05 kHz */\n     {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464,\n      522, 576},\n     {0, 4, 8, 12, 18, 24, 32, 42, 56, 74, 100, 132, 174, 192}\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */\n     },\n    {                   /* Table B.2.c: 24 kHz */ /* docs: 332. mpg123(broken): 330 */\n     {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 114, 136, 162, 194, 232, 278, 332, 394, 464,\n      540, 576},\n     {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 136, 180, 192}\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */\n     },\n    {                   /* Table B.2.a: 16 kHz */\n     {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464,\n      522, 576},\n     {0, 4, 8, 12, 18, 26, 36, 48, 62, 80, 104, 134, 174, 192}\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */\n     },\n    {                   /* Table B.8.b: 44.1 kHz */\n     {0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 52, 62, 74, 90, 110, 134, 162, 196, 238, 288, 342, 418,\n      576},\n     {0, 4, 8, 12, 16, 22, 30, 40, 52, 66, 84, 106, 136, 192}\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */\n     },\n    {                   /* Table B.8.c: 48 kHz */\n     {0, 4, 8, 12, 16, 20, 24, 30, 36, 42, 50, 60, 72, 88, 106, 128, 156, 190, 230, 276, 330, 384,\n      576},\n     {0, 4, 8, 12, 16, 22, 28, 38, 50, 64, 80, 100, 126, 192}\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */\n     },\n    {                   /* Table B.8.a: 32 kHz */\n     {0, 4, 8, 12, 16, 20, 24, 30, 36, 44, 54, 66, 82, 102, 126, 156, 194, 240, 296, 364, 448, 550,\n      576},\n     {0, 4, 8, 12, 16, 22, 30, 42, 58, 78, 104, 138, 180, 192}\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */\n     },\n    {                   /* MPEG-2.5 11.025 kHz */\n     {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464,\n      522, 576},\n     {0 / 3, 12 / 3, 24 / 3, 36 / 3, 54 / 3, 78 / 3, 108 / 3, 144 / 3, 186 / 3, 240 / 3, 312 / 3,\n      402 / 3, 522 / 3, 576 / 3}\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */\n     },\n    {                   /* MPEG-2.5 12 kHz */\n     {0, 6, 12, 18, 24, 30, 36, 44, 54, 66, 80, 96, 116, 140, 168, 200, 238, 284, 336, 396, 464,\n      522, 576},\n     {0 / 3, 12 / 3, 24 / 3, 36 / 3, 54 / 3, 78 / 3, 108 / 3, 144 / 3, 186 / 3, 240 / 3, 312 / 3,\n      402 / 3, 522 / 3, 576 / 3}\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */\n     },\n    {                   /* MPEG-2.5 8 kHz */\n     {0, 12, 24, 36, 48, 60, 72, 88, 108, 132, 160, 192, 232, 280, 336, 400, 476, 566, 568, 570,\n      572, 574, 576},\n     {0 / 3, 24 / 3, 48 / 3, 72 / 3, 108 / 3, 156 / 3, 216 / 3, 288 / 3, 372 / 3, 480 / 3, 486 / 3,\n      492 / 3, 498 / 3, 576 / 3}\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb21 pseudo sub bands */\n     , {0, 0, 0, 0, 0, 0, 0} /*  sfb12 pseudo sub bands */\n     }\n};\n\n\n\nFLOAT   pow20[Q_MAX + Q_MAX2 + 1];\nFLOAT   ipow20[Q_MAX];\nFLOAT   pow43[PRECALC_SIZE];\n/* initialized in first call to iteration_init */\n#ifdef TAKEHIRO_IEEE754_HACK\nFLOAT   adj43asm[PRECALC_SIZE];\n#else\nFLOAT   adj43[PRECALC_SIZE];\n#endif\n\n/* \ncompute the ATH for each scalefactor band \ncd range:  0..96db\n\nInput:  3.3kHz signal  32767 amplitude  (3.3kHz is where ATH is smallest = -5db)\nlongblocks:  sfb=12   en0/bw=-11db    max_en0 = 1.3db\nshortblocks: sfb=5           -9db              0db\n\nInput:  1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 (repeated)\nlongblocks:  amp=1      sfb=12   en0/bw=-103 db      max_en0 = -92db\n            amp=32767   sfb=12           -12 db                 -1.4db \n\nInput:  1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 -1 (repeated)\nshortblocks: amp=1      sfb=5   en0/bw= -99                    -86 \n            amp=32767   sfb=5           -9  db                  4db \n\n\nMAX energy of largest wave at 3.3kHz = 1db\nAVE energy of largest wave at 3.3kHz = -11db\nLet's take AVE:  -11db = maximum signal in sfb=12.  \nDynamic range of CD: 96db.  Therefor energy of smallest audible wave \nin sfb=12  = -11  - 96 = -107db = ATH at 3.3kHz.  \n\nATH formula for this wave: -5db.  To adjust to LAME scaling, we need\nATH = ATH_formula  - 103  (db)\nATH = ATH * 2.5e-10      (ener)\n\n*/\n\nstatic  FLOAT\nATHmdct(SessionConfig_t const *cfg, FLOAT f)\n{\n    FLOAT   ath;\n\n    ath = ATHformula(cfg, f);\n\n    if (cfg->ATHfixpoint > 0) {\n        ath -= cfg->ATHfixpoint;\n    }\n    else {\n        ath -= NSATHSCALE;\n    }\n    ath += cfg->ATH_offset_db;\n\n    /* modify the MDCT scaling for the ATH and convert to energy */\n    ath = powf(10.0f, ath * 0.1f);\n    return ath;\n}\n\nstatic void\ncompute_ath(lame_internal_flags const* gfc)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    FLOAT  *const ATH_l = gfc->ATH->l;\n    FLOAT  *const ATH_psfb21 = gfc->ATH->psfb21;\n    FLOAT  *const ATH_s = gfc->ATH->s;\n    FLOAT  *const ATH_psfb12 = gfc->ATH->psfb12;\n    int     sfb, i, start, end;\n    FLOAT   ATH_f;\n    FLOAT const samp_freq = cfg->samplerate_out;\n\n    for (sfb = 0; sfb < SBMAX_l; sfb++) {\n        start = gfc->scalefac_band.l[sfb];\n        end = gfc->scalefac_band.l[sfb + 1];\n        ATH_l[sfb] = FLOAT_MAX;\n        for (i = start; i < end; i++) {\n            FLOAT const freq = i * samp_freq / (2 * 576);\n            ATH_f = ATHmdct(cfg, freq); /* freq in kHz */\n            ATH_l[sfb] = Min(ATH_l[sfb], ATH_f);\n        }\n    }\n\n    for (sfb = 0; sfb < PSFB21; sfb++) {\n        start = gfc->scalefac_band.psfb21[sfb];\n        end = gfc->scalefac_band.psfb21[sfb + 1];\n        ATH_psfb21[sfb] = FLOAT_MAX;\n        for (i = start; i < end; i++) {\n            FLOAT const freq = i * samp_freq / (2 * 576);\n            ATH_f = ATHmdct(cfg, freq); /* freq in kHz */\n            ATH_psfb21[sfb] = Min(ATH_psfb21[sfb], ATH_f);\n        }\n    }\n\n    for (sfb = 0; sfb < SBMAX_s; sfb++) {\n        start = gfc->scalefac_band.s[sfb];\n        end = gfc->scalefac_band.s[sfb + 1];\n        ATH_s[sfb] = FLOAT_MAX;\n        for (i = start; i < end; i++) {\n            FLOAT const freq = i * samp_freq / (2 * 192);\n            ATH_f = ATHmdct(cfg, freq); /* freq in kHz */\n            ATH_s[sfb] = Min(ATH_s[sfb], ATH_f);\n        }\n        ATH_s[sfb] *= (gfc->scalefac_band.s[sfb + 1] - gfc->scalefac_band.s[sfb]);\n    }\n\n    for (sfb = 0; sfb < PSFB12; sfb++) {\n        start = gfc->scalefac_band.psfb12[sfb];\n        end = gfc->scalefac_band.psfb12[sfb + 1];\n        ATH_psfb12[sfb] = FLOAT_MAX;\n        for (i = start; i < end; i++) {\n            FLOAT const freq = i * samp_freq / (2 * 192);\n            ATH_f = ATHmdct(cfg, freq); /* freq in kHz */\n            ATH_psfb12[sfb] = Min(ATH_psfb12[sfb], ATH_f);\n        }\n        /*not sure about the following */\n        ATH_psfb12[sfb] *= (gfc->scalefac_band.s[13] - gfc->scalefac_band.s[12]);\n    }\n\n\n    /*  no-ATH mode:\n     *  reduce ATH to -200 dB\n     */\n\n    if (cfg->noATH) {\n        for (sfb = 0; sfb < SBMAX_l; sfb++) {\n            ATH_l[sfb] = 1E-20;\n        }\n        for (sfb = 0; sfb < PSFB21; sfb++) {\n            ATH_psfb21[sfb] = 1E-20;\n        }\n        for (sfb = 0; sfb < SBMAX_s; sfb++) {\n            ATH_s[sfb] = 1E-20;\n        }\n        for (sfb = 0; sfb < PSFB12; sfb++) {\n            ATH_psfb12[sfb] = 1E-20;\n        }\n    }\n\n    /*  work in progress, don't rely on it too much\n     */\n    gfc->ATH->floor = 10. * log10(ATHmdct(cfg, -1.));\n\n    /*\n       {   FLOAT g=10000, t=1e30, x;\n       for ( f = 100; f < 10000; f++ ) {\n       x = ATHmdct( cfg, f );\n       if ( t > x ) t = x, g = f;\n       }\n       printf(\"min=%g\\n\", g);\n       } */\n}\n\n\nstatic float const payload_long[2][4] = \n{ {-0.000f, -0.000f, -0.000f, +0.000f}\n, {-0.500f, -0.250f, -0.025f, +0.500f}\n};\nstatic float const payload_short[2][4] = \n{ {-0.000f, -0.000f, -0.000f, +0.000f}\n, {-2.000f, -1.000f, -0.050f, +0.500f}\n};\n\n/************************************************************************/\n/*  initialization for iteration_loop */\n/************************************************************************/\nvoid\niteration_init(lame_internal_flags * gfc)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    III_side_info_t *const l3_side = &gfc->l3_side;\n    FLOAT   adjust, db;\n    int     i, sel;\n\n    if (gfc->iteration_init_init == 0) {\n        gfc->iteration_init_init = 1;\n\n        l3_side->main_data_begin = 0;\n        compute_ath(gfc);\n\n        pow43[0] = 0.0;\n        for (i = 1; i < PRECALC_SIZE; i++)\n            pow43[i] = pow((FLOAT) i, 4.0 / 3.0);\n\n#ifdef TAKEHIRO_IEEE754_HACK\n        adj43asm[0] = 0.0;\n        for (i = 1; i < PRECALC_SIZE; i++)\n            adj43asm[i] = i - 0.5 - pow(0.5 * (pow43[i - 1] + pow43[i]), 0.75);\n#else\n        for (i = 0; i < PRECALC_SIZE - 1; i++)\n            adj43[i] = (i + 1) - pow(0.5 * (pow43[i] + pow43[i + 1]), 0.75);\n        adj43[i] = 0.5;\n#endif\n        for (i = 0; i < Q_MAX; i++)\n            ipow20[i] = pow(2.0, (double) (i - 210) * -0.1875);\n        for (i = 0; i <= Q_MAX + Q_MAX2; i++)\n            pow20[i] = pow(2.0, (double) (i - 210 - Q_MAX2) * 0.25);\n\n        huffman_init(gfc);\n        init_xrpow_core_init(gfc);\n\n        sel = 1;/* RH: all modes like vbr-new (cfg->vbr == vbr_mt || cfg->vbr == vbr_mtrh) ? 1 : 0;*/\n\n        /* long */\n        db = cfg->adjust_bass_db + payload_long[sel][0];\n        adjust = powf(10.f, db * 0.1f);\n        for (i = 0; i <= 6; ++i) {\n            gfc->sv_qnt.longfact[i] = adjust;\n        }\n        db = cfg->adjust_alto_db + payload_long[sel][1];\n        adjust = powf(10.f, db * 0.1f);\n        for (; i <= 13; ++i) {\n            gfc->sv_qnt.longfact[i] = adjust;\n        }\n        db = cfg->adjust_treble_db + payload_long[sel][2];\n        adjust = powf(10.f, db * 0.1f);\n        for (; i <= 20; ++i) {\n            gfc->sv_qnt.longfact[i] = adjust;\n        }\n        db = cfg->adjust_sfb21_db + payload_long[sel][3];\n        adjust = powf(10.f, db * 0.1f);\n        for (; i < SBMAX_l; ++i) {\n            gfc->sv_qnt.longfact[i] = adjust;\n        }\n\n        /* short */\n        db = cfg->adjust_bass_db + payload_short[sel][0];\n        adjust = powf(10.f, db * 0.1f);\n        for (i = 0; i <= 2; ++i) {\n            gfc->sv_qnt.shortfact[i] = adjust;\n        }\n        db = cfg->adjust_alto_db + payload_short[sel][1];\n        adjust = powf(10.f, db * 0.1f);\n        for (; i <= 6; ++i) {\n            gfc->sv_qnt.shortfact[i] = adjust;\n        }\n        db = cfg->adjust_treble_db + payload_short[sel][2];\n        adjust = powf(10.f, db * 0.1f);\n        for (; i <= 11; ++i) {\n            gfc->sv_qnt.shortfact[i] = adjust;\n        }\n        db = cfg->adjust_sfb21_db + payload_short[sel][3];\n        adjust = powf(10.f, db * 0.1f);\n        for (; i < SBMAX_s; ++i) {\n            gfc->sv_qnt.shortfact[i] = adjust;\n        }\n    }\n}\n\n\n\n\n\n/************************************************************************\n * allocate bits among 2 channels based on PE\n * mt 6/99\n * bugfixes rh 8/01: often allocated more than the allowed 4095 bits\n ************************************************************************/\nint\non_pe(lame_internal_flags * gfc, const FLOAT pe[][2], int targ_bits[2], int mean_bits, int gr, int cbr)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     extra_bits = 0, tbits, bits;\n    int     add_bits[2] = {0, 0};\n    int     max_bits;        /* maximum allowed bits for this granule */\n    int     ch;\n\n    /* allocate targ_bits for granule */\n    ResvMaxBits(gfc, mean_bits, &tbits, &extra_bits, cbr);\n    max_bits = tbits + extra_bits;\n    if (max_bits > MAX_BITS_PER_GRANULE) /* hard limit per granule */\n        max_bits = MAX_BITS_PER_GRANULE;\n\n    for (bits = 0, ch = 0; ch < cfg->channels_out; ++ch) {\n        /******************************************************************\n         * allocate bits for each channel \n         ******************************************************************/\n        targ_bits[ch] = Min(MAX_BITS_PER_CHANNEL, tbits / cfg->channels_out);\n\n        add_bits[ch] = targ_bits[ch] * pe[gr][ch] / 700.0 - targ_bits[ch];\n\n        /* at most increase bits by 1.5*average */\n        if (add_bits[ch] > mean_bits * 3 / 4)\n            add_bits[ch] = mean_bits * 3 / 4;\n        if (add_bits[ch] < 0)\n            add_bits[ch] = 0;\n\n        if (add_bits[ch] + targ_bits[ch] > MAX_BITS_PER_CHANNEL)\n            add_bits[ch] = Max(0, MAX_BITS_PER_CHANNEL - targ_bits[ch]);\n\n        bits += add_bits[ch];\n    }\n    if (bits > extra_bits && bits > 0) {\n        for (ch = 0; ch < cfg->channels_out; ++ch) {\n            add_bits[ch] = extra_bits * add_bits[ch] / bits;\n        }\n    }\n\n    for (ch = 0; ch < cfg->channels_out; ++ch) {\n        targ_bits[ch] += add_bits[ch];\n        extra_bits -= add_bits[ch];\n    }\n\n    for (bits = 0, ch = 0; ch < cfg->channels_out; ++ch) {\n        bits += targ_bits[ch];\n    }\n    if (bits > MAX_BITS_PER_GRANULE) {\n        int     sum = 0;\n        for (ch = 0; ch < cfg->channels_out; ++ch) {\n            targ_bits[ch] *= MAX_BITS_PER_GRANULE;\n            targ_bits[ch] /= bits;\n            sum += targ_bits[ch];\n        }\n        assert(sum <= MAX_BITS_PER_GRANULE);\n    }\n\n    return max_bits;\n}\n\n\n\n\nvoid\nreduce_side(int targ_bits[2], FLOAT ms_ener_ratio, int mean_bits, int max_bits)\n{\n    int     move_bits;\n    FLOAT   fac;\n\n    assert(max_bits <= MAX_BITS_PER_GRANULE);\n    assert(targ_bits[0] + targ_bits[1] <= MAX_BITS_PER_GRANULE);\n\n    /*  ms_ener_ratio = 0:  allocate 66/33  mid/side  fac=.33  \n     *  ms_ener_ratio =.5:  allocate 50/50 mid/side   fac= 0 */\n    /* 75/25 split is fac=.5 */\n    /* float fac = .50*(.5-ms_ener_ratio[gr])/.5; */\n    fac = .33 * (.5 - ms_ener_ratio) / .5;\n    if (fac < 0)\n        fac = 0;\n    if (fac > .5)\n        fac = .5;\n\n    /* number of bits to move from side channel to mid channel */\n    /*    move_bits = fac*targ_bits[1];  */\n    move_bits = fac * .5 * (targ_bits[0] + targ_bits[1]);\n\n    if (move_bits > MAX_BITS_PER_CHANNEL - targ_bits[0]) {\n        move_bits = MAX_BITS_PER_CHANNEL - targ_bits[0];\n    }\n    if (move_bits < 0)\n        move_bits = 0;\n\n    if (targ_bits[1] >= 125) {\n        /* dont reduce side channel below 125 bits */\n        if (targ_bits[1] - move_bits > 125) {\n\n            /* if mid channel already has 2x more than average, dont bother */\n            /* mean_bits = bits per granule (for both channels) */\n            if (targ_bits[0] < mean_bits)\n                targ_bits[0] += move_bits;\n            targ_bits[1] -= move_bits;\n        }\n        else {\n            targ_bits[0] += targ_bits[1] - 125;\n            targ_bits[1] = 125;\n        }\n    }\n\n    move_bits = targ_bits[0] + targ_bits[1];\n    if (move_bits > max_bits) {\n        targ_bits[0] = (max_bits * targ_bits[0]) / move_bits;\n        targ_bits[1] = (max_bits * targ_bits[1]) / move_bits;\n    }\n    assert(targ_bits[0] <= MAX_BITS_PER_CHANNEL);\n    assert(targ_bits[1] <= MAX_BITS_PER_CHANNEL);\n    assert(targ_bits[0] + targ_bits[1] <= MAX_BITS_PER_GRANULE);\n}\n\n\n/**\n *  Robert Hegemann 2001-04-27:\n *  this adjusts the ATH, keeping the original noise floor\n *  affects the higher frequencies more than the lower ones\n */\n\nFLOAT\nathAdjust(FLOAT a, FLOAT x, FLOAT athFloor, float ATHfixpoint)\n{\n    /*  work in progress\n     */\n    FLOAT const o = 90.30873362f;\n    FLOAT const p = (ATHfixpoint < 1.f) ? 94.82444863f : ATHfixpoint;\n    FLOAT   u = FAST_LOG10_X(x, 10.0f);\n    FLOAT const v = a * a;\n    FLOAT   w = 0.0f;\n    u -= athFloor;      /* undo scaling */\n    if (v > 1E-20f)\n        w = 1.f + FAST_LOG10_X(v, 10.0f / o);\n    if (w < 0)\n        w = 0.f;\n    u *= w;\n    u += athFloor + o - p; /* redo scaling */\n\n    return powf(10.f, 0.1f * u);\n}\n\n\n\n/*************************************************************************/\n/*            calc_xmin                                                  */\n/*************************************************************************/\n\n/*\n  Calculate the allowed distortion for each scalefactor band,\n  as determined by the psychoacoustic model.\n  xmin(sb) = ratio(sb) * en(sb) / bw(sb)\n\n  returns number of sfb's with energy > ATH\n*/\n\nint\ncalc_xmin(lame_internal_flags const *gfc,\n          III_psy_ratio const *const ratio, gr_info * const cod_info, FLOAT * pxmin)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     sfb, gsfb, j = 0, ath_over = 0, k;\n    ATH_t const *const ATH = gfc->ATH;\n    const FLOAT *const xr = cod_info->xr;\n    int     max_nonzero;\n\n    for (gsfb = 0; gsfb < cod_info->psy_lmax; gsfb++) {\n        FLOAT   en0, xmin;\n        FLOAT   rh1, rh2, rh3;\n        int     width, l;\n\n        xmin = athAdjust(ATH->adjust_factor, ATH->l[gsfb], ATH->floor, cfg->ATHfixpoint);\n        xmin *= gfc->sv_qnt.longfact[gsfb];\n\n        width = cod_info->width[gsfb];\n        rh1 = xmin / width;\n#ifdef DBL_EPSILON\n        rh2 = DBL_EPSILON;\n#else\n        rh2 = 2.2204460492503131e-016;\n#endif\n        en0 = 0.0;\n        for (l = 0; l < width; ++l) {\n            FLOAT const xa = xr[j++];\n            FLOAT const x2 = xa * xa;\n            en0 += x2;\n            rh2 += (x2 < rh1) ? x2 : rh1;\n        }\n        if (en0 > xmin)\n            ath_over++;\n\n        if (en0 < xmin) {\n            rh3 = en0;\n        }\n        else if (rh2 < xmin) {\n            rh3 = xmin;\n        }\n        else {\n            rh3 = rh2;\n        }\n        xmin = rh3;\n        {\n            FLOAT const e = ratio->en.l[gsfb];\n            if (e > 1e-12f) {\n                FLOAT   x;\n                x = en0 * ratio->thm.l[gsfb] / e;\n                x *= gfc->sv_qnt.longfact[gsfb];\n                if (xmin < x)\n                    xmin = x;\n            }\n        }\n        xmin = Max(xmin, DBL_EPSILON);\n        cod_info->energy_above_cutoff[gsfb] = (en0 > xmin+1e-14f) ? 1 : 0;\n        *pxmin++ = xmin;\n    }                   /* end of long block loop */\n\n\n\n\n    /*use this function to determine the highest non-zero coeff */\n    max_nonzero = 0;\n    for (k = 575; k > 0; --k) {\n        if (fabs(xr[k]) > 1e-12f) {\n            max_nonzero = k;\n            break;\n        }\n    }\n    if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type, but not SHORT */\n        max_nonzero |= 1; /* only odd numbers */\n    }\n    else {\n        max_nonzero /= 6; /* 3 short blocks */\n        max_nonzero *= 6;\n        max_nonzero += 5;\n    }\n\n    if (gfc->sv_qnt.sfb21_extra == 0 && cfg->samplerate_out < 44000) {\n      int const sfb_l = (cfg->samplerate_out <= 8000) ? 17 : 21;\n      int const sfb_s = (cfg->samplerate_out <= 8000) ?  9 : 12;\n      int   limit = 575;\n      if (cod_info->block_type != SHORT_TYPE) { /* NORM, START or STOP type, but not SHORT */\n          limit = gfc->scalefac_band.l[sfb_l]-1;\n      }\n      else {\n          limit = 3*gfc->scalefac_band.s[sfb_s]-1;\n      }\n      if (max_nonzero > limit) {\n          max_nonzero = limit;\n      }\n    }\n    cod_info->max_nonzero_coeff = max_nonzero;\n\n\n\n    for (sfb = cod_info->sfb_smin; gsfb < cod_info->psymax; sfb++, gsfb += 3) {\n        int     width, b, l;\n        FLOAT   tmpATH;\n\n        tmpATH = athAdjust(ATH->adjust_factor, ATH->s[sfb], ATH->floor, cfg->ATHfixpoint);\n        tmpATH *= gfc->sv_qnt.shortfact[sfb];\n        \n        width = cod_info->width[gsfb];\n        for (b = 0; b < 3; b++) {\n            FLOAT   en0 = 0.0, xmin = tmpATH;\n            FLOAT   rh1, rh2, rh3;\n\n            rh1 = tmpATH / width;\n#ifdef DBL_EPSILON\n            rh2 = DBL_EPSILON;\n#else\n            rh2 = 2.2204460492503131e-016;\n#endif\n            for (l = 0; l < width; ++l) {\n                FLOAT const xa = xr[j++];\n                FLOAT const x2 = xa * xa;\n                en0 += x2;\n                rh2 += (x2 < rh1) ? x2 : rh1;\n            }\n            if (en0 > tmpATH)\n                ath_over++;\n            \n            if (en0 < tmpATH) {\n                rh3 = en0;\n            }\n            else if (rh2 < tmpATH) {\n                rh3 = tmpATH;\n            }\n            else {\n                rh3 = rh2;\n            }\n            xmin = rh3;\n            {\n                FLOAT const e = ratio->en.s[sfb][b];\n                if (e > 1e-12f) {\n                    FLOAT   x;\n                    x = en0 * ratio->thm.s[sfb][b] / e;\n                    x *= gfc->sv_qnt.shortfact[sfb];\n                    if (xmin < x)\n                        xmin = x;\n                }\n            }\n            xmin = Max(xmin, DBL_EPSILON);\n            cod_info->energy_above_cutoff[gsfb+b] = (en0 > xmin+1e-14f) ? 1 : 0;\n            *pxmin++ = xmin;\n        }               /* b */\n        if (cfg->use_temporal_masking_effect) {\n            if (pxmin[-3] > pxmin[-3 + 1])\n                pxmin[-3 + 1] += (pxmin[-3] - pxmin[-3 + 1]) * gfc->cd_psy->decay;\n            if (pxmin[-3 + 1] > pxmin[-3 + 2])\n                pxmin[-3 + 2] += (pxmin[-3 + 1] - pxmin[-3 + 2]) * gfc->cd_psy->decay;\n        }\n    }                   /* end of short block sfb loop */\n\n    return ath_over;\n}\n\n\nstatic  FLOAT\ncalc_noise_core_c(const gr_info * const cod_info, int *startline, int l, FLOAT step)\n{\n    FLOAT   noise = 0;\n    int     j = *startline;\n    const int *const ix = cod_info->l3_enc;\n\n    if (j > cod_info->count1) {\n        while (l--) {\n            FLOAT   temp;\n            temp = cod_info->xr[j];\n            j++;\n            noise += temp * temp;\n            temp = cod_info->xr[j];\n            j++;\n            noise += temp * temp;\n        }\n    }\n    else if (j > cod_info->big_values) {\n        FLOAT   ix01[2];\n        ix01[0] = 0;\n        ix01[1] = step;\n        while (l--) {\n            FLOAT   temp;\n            temp = fabs(cod_info->xr[j]) - ix01[ix[j]];\n            j++;\n            noise += temp * temp;\n            temp = fabs(cod_info->xr[j]) - ix01[ix[j]];\n            j++;\n            noise += temp * temp;\n        }\n    }\n    else {\n        while (l--) {\n            FLOAT   temp;\n            temp = fabs(cod_info->xr[j]) - pow43[ix[j]] * step;\n            j++;\n            noise += temp * temp;\n            temp = fabs(cod_info->xr[j]) - pow43[ix[j]] * step;\n            j++;\n            noise += temp * temp;\n        }\n    }\n\n    *startline = j;\n    return noise;\n}\n\n\n/*************************************************************************/\n/*            calc_noise                                                 */\n/*************************************************************************/\n\n/* -oo dB  =>  -1.00 */\n/* - 6 dB  =>  -0.97 */\n/* - 3 dB  =>  -0.80 */\n/* - 2 dB  =>  -0.64 */\n/* - 1 dB  =>  -0.38 */\n/*   0 dB  =>   0.00 */\n/* + 1 dB  =>  +0.49 */\n/* + 2 dB  =>  +1.06 */\n/* + 3 dB  =>  +1.68 */\n/* + 6 dB  =>  +3.69 */\n/* +10 dB  =>  +6.45 */\n\nint\ncalc_noise(gr_info const *const cod_info,\n           FLOAT const *l3_xmin,\n           FLOAT * distort, calc_noise_result * const res, calc_noise_data * prev_noise)\n{\n    int     sfb, l, over = 0;\n    FLOAT   over_noise_db = 0;\n    FLOAT   tot_noise_db = 0; /*    0 dB relative to masking */\n    FLOAT   max_noise = -20.0; /* -200 dB relative to masking */\n    int     j = 0;\n    const int *scalefac = cod_info->scalefac;\n\n    res->over_SSD = 0;\n\n\n    for (sfb = 0; sfb < cod_info->psymax; sfb++) {\n        int const s =\n            cod_info->global_gain - (((*scalefac++) + (cod_info->preflag ? pretab[sfb] : 0))\n                                     << (cod_info->scalefac_scale + 1))\n            - cod_info->subblock_gain[cod_info->window[sfb]] * 8;\n        FLOAT const r_l3_xmin = 1.f / *l3_xmin++;\n        FLOAT   distort_ = 0.0f;\n        FLOAT   noise = 0.0f;\n\n        if (prev_noise && (prev_noise->step[sfb] == s)) {\n\n            /* use previously computed values */\n            j += cod_info->width[sfb];\n            distort_ = r_l3_xmin * prev_noise->noise[sfb];\n\n            noise = prev_noise->noise_log[sfb];\n\n        }\n        else {\n            FLOAT const step = POW20(s);\n            l = cod_info->width[sfb] >> 1;\n\n            if ((j + cod_info->width[sfb]) > cod_info->max_nonzero_coeff) {\n                int     usefullsize;\n                usefullsize = cod_info->max_nonzero_coeff - j + 1;\n\n                if (usefullsize > 0)\n                    l = usefullsize >> 1;\n                else\n                    l = 0;\n            }\n\n            noise = calc_noise_core_c(cod_info, &j, l, step);\n\n\n            if (prev_noise) {\n                /* save noise values */\n                prev_noise->step[sfb] = s;\n                prev_noise->noise[sfb] = noise;\n            }\n\n            distort_ = r_l3_xmin * noise;\n\n            /* multiplying here is adding in dB, but can overflow */\n            noise = FAST_LOG10(Max(distort_, 1E-20f));\n\n            if (prev_noise) {\n                /* save noise values */\n                prev_noise->noise_log[sfb] = noise;\n            }\n        }\n        *distort++ = distort_;\n\n        if (prev_noise) {\n            /* save noise values */\n            prev_noise->global_gain = cod_info->global_gain;;\n        }\n\n\n        /*tot_noise *= Max(noise, 1E-20); */\n        tot_noise_db += noise;\n\n        if (noise > 0.0) {\n            int     tmp;\n\n            tmp = Max((int) (noise * 10 + .5), 1);\n            res->over_SSD += tmp * tmp;\n\n            over++;\n            /* multiplying here is adding in dB -but can overflow */\n            /*over_noise *= noise; */\n            over_noise_db += noise;\n        }\n        max_noise = Max(max_noise, noise);\n\n    }\n\n    res->over_count = over;\n    res->tot_noise = tot_noise_db;\n    res->over_noise = over_noise_db;\n    res->max_noise = max_noise;\n\n    return over;\n}\n\n\n\n\n\n\n\n\n/************************************************************************\n *\n *  set_pinfo()\n *\n *  updates plotting data    \n *\n *  Mark Taylor 2000-??-??                \n *\n *  Robert Hegemann: moved noise/distortion calc into it\n *\n ************************************************************************/\n\nstatic void\nset_pinfo(lame_internal_flags const *gfc,\n          gr_info * const cod_info, const III_psy_ratio * const ratio, const int gr, const int ch)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     sfb, sfb2;\n    int     j, i, l, start, end, bw;\n    FLOAT   en0, en1;\n    FLOAT const ifqstep = (cod_info->scalefac_scale == 0) ? .5 : 1.0;\n    int const *const scalefac = cod_info->scalefac;\n\n    FLOAT   l3_xmin[SFBMAX], xfsf[SFBMAX];\n    calc_noise_result noise;\n\n    (void) calc_xmin(gfc, ratio, cod_info, l3_xmin);\n    (void) calc_noise(cod_info, l3_xmin, xfsf, &noise, 0);\n\n    j = 0;\n    sfb2 = cod_info->sfb_lmax;\n    if (cod_info->block_type != SHORT_TYPE && !cod_info->mixed_block_flag)\n        sfb2 = 22;\n    for (sfb = 0; sfb < sfb2; sfb++) {\n        start = gfc->scalefac_band.l[sfb];\n        end = gfc->scalefac_band.l[sfb + 1];\n        bw = end - start;\n        for (en0 = 0.0; j < end; j++)\n            en0 += cod_info->xr[j] * cod_info->xr[j];\n        en0 /= bw;\n        /* convert to MDCT units */\n        en1 = 1e15;     /* scaling so it shows up on FFT plot */\n        gfc->pinfo->en[gr][ch][sfb] = en1 * en0;\n        gfc->pinfo->xfsf[gr][ch][sfb] = en1 * l3_xmin[sfb] * xfsf[sfb] / bw;\n\n        if (ratio->en.l[sfb] > 0 && !cfg->ATHonly)\n            en0 = en0 / ratio->en.l[sfb];\n        else\n            en0 = 0.0;\n\n        gfc->pinfo->thr[gr][ch][sfb] = en1 * Max(en0 * ratio->thm.l[sfb], gfc->ATH->l[sfb]);\n\n        /* there is no scalefactor bands >= SBPSY_l */\n        gfc->pinfo->LAMEsfb[gr][ch][sfb] = 0;\n        if (cod_info->preflag && sfb >= 11)\n            gfc->pinfo->LAMEsfb[gr][ch][sfb] = -ifqstep * pretab[sfb];\n\n        if (sfb < SBPSY_l) {\n            assert(scalefac[sfb] >= 0); /* scfsi should be decoded by caller side */\n            gfc->pinfo->LAMEsfb[gr][ch][sfb] -= ifqstep * scalefac[sfb];\n        }\n    }                   /* for sfb */\n\n    if (cod_info->block_type == SHORT_TYPE) {\n        sfb2 = sfb;\n        for (sfb = cod_info->sfb_smin; sfb < SBMAX_s; sfb++) {\n            start = gfc->scalefac_band.s[sfb];\n            end = gfc->scalefac_band.s[sfb + 1];\n            bw = end - start;\n            for (i = 0; i < 3; i++) {\n                for (en0 = 0.0, l = start; l < end; l++) {\n                    en0 += cod_info->xr[j] * cod_info->xr[j];\n                    j++;\n                }\n                en0 = Max(en0 / bw, 1e-20);\n                /* convert to MDCT units */\n                en1 = 1e15; /* scaling so it shows up on FFT plot */\n\n                gfc->pinfo->en_s[gr][ch][3 * sfb + i] = en1 * en0;\n                gfc->pinfo->xfsf_s[gr][ch][3 * sfb + i] = en1 * l3_xmin[sfb2] * xfsf[sfb2] / bw;\n                if (ratio->en.s[sfb][i] > 0)\n                    en0 = en0 / ratio->en.s[sfb][i];\n                else\n                    en0 = 0.0;\n                if (cfg->ATHonly || cfg->ATHshort)\n                    en0 = 0;\n\n                gfc->pinfo->thr_s[gr][ch][3 * sfb + i] =\n                    en1 * Max(en0 * ratio->thm.s[sfb][i], gfc->ATH->s[sfb]);\n\n                /* there is no scalefactor bands >= SBPSY_s */\n                gfc->pinfo->LAMEsfb_s[gr][ch][3 * sfb + i]\n                    = -2.0 * cod_info->subblock_gain[i];\n                if (sfb < SBPSY_s) {\n                    gfc->pinfo->LAMEsfb_s[gr][ch][3 * sfb + i] -= ifqstep * scalefac[sfb2];\n                }\n                sfb2++;\n            }\n        }\n    }                   /* block type short */\n    gfc->pinfo->LAMEqss[gr][ch] = cod_info->global_gain;\n    gfc->pinfo->LAMEmainbits[gr][ch] = cod_info->part2_3_length + cod_info->part2_length;\n    gfc->pinfo->LAMEsfbits[gr][ch] = cod_info->part2_length;\n\n    gfc->pinfo->over[gr][ch] = noise.over_count;\n    gfc->pinfo->max_noise[gr][ch] = noise.max_noise * 10.0;\n    gfc->pinfo->over_noise[gr][ch] = noise.over_noise * 10.0;\n    gfc->pinfo->tot_noise[gr][ch] = noise.tot_noise * 10.0;\n    gfc->pinfo->over_SSD[gr][ch] = noise.over_SSD;\n}\n\n\n/************************************************************************\n *\n *  set_frame_pinfo()\n *\n *  updates plotting data for a whole frame  \n *\n *  Robert Hegemann 2000-10-21                          \n *\n ************************************************************************/\n\nvoid\nset_frame_pinfo(lame_internal_flags * gfc, const III_psy_ratio ratio[2][2])\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     ch;\n    int     gr;\n\n    /* for every granule and channel patch l3_enc and set info\n     */\n    for (gr = 0; gr < cfg->mode_gr; gr++) {\n        for (ch = 0; ch < cfg->channels_out; ch++) {\n            gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];\n            int     scalefac_sav[SFBMAX];\n            memcpy(scalefac_sav, cod_info->scalefac, sizeof(scalefac_sav));\n\n            /* reconstruct the scalefactors in case SCFSI was used \n             */\n            if (gr == 1) {\n                int     sfb;\n                for (sfb = 0; sfb < cod_info->sfb_lmax; sfb++) {\n                    if (cod_info->scalefac[sfb] < 0) /* scfsi */\n                        cod_info->scalefac[sfb] = gfc->l3_side.tt[0][ch].scalefac[sfb];\n                }\n            }\n\n            set_pinfo(gfc, cod_info, &ratio[gr][ch], gr, ch);\n            memcpy(cod_info->scalefac, scalefac_sav, sizeof(scalefac_sav));\n        }               /* for ch */\n    }                   /* for gr */\n}\n"
  },
  {
    "path": "app/jni/libmp3lame/quantize_pvt.h",
    "content": "/*\n *\tquantize_pvt include file\n *\n *\tCopyright (c) 1999 Takehiro TOMINAGA\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_QUANTIZE_PVT_H\n#define LAME_QUANTIZE_PVT_H\n\n#define IXMAX_VAL 8206  /* ix always <= 8191+15.    see count_bits() */\n\n/* buggy Winamp decoder cannot handle values > 8191 */\n/* #define IXMAX_VAL 8191 */\n\n#define PRECALC_SIZE (IXMAX_VAL+2)\n\n\nextern const int nr_of_sfb_block[6][3][4];\nextern const int pretab[SBMAX_l];\nextern const int slen1_tab[16];\nextern const int slen2_tab[16];\n\nextern const scalefac_struct sfBandIndex[9];\n\nextern FLOAT pow43[PRECALC_SIZE];\n#ifdef TAKEHIRO_IEEE754_HACK\nextern FLOAT adj43asm[PRECALC_SIZE];\n#else\nextern FLOAT adj43[PRECALC_SIZE];\n#endif\n\n#define Q_MAX (256+1)\n#define Q_MAX2 116      /* minimum possible number of\n                           -cod_info->global_gain\n                           + ((scalefac[] + (cod_info->preflag ? pretab[sfb] : 0))\n                           << (cod_info->scalefac_scale + 1))\n                           + cod_info->subblock_gain[cod_info->window[sfb]] * 8;\n\n                           for long block, 0+((15+3)<<2) = 18*4 = 72\n                           for short block, 0+(15<<2)+7*8 = 15*4+56 = 116\n                         */\n\nextern FLOAT pow20[Q_MAX + Q_MAX2 + 1];\nextern FLOAT ipow20[Q_MAX];\n\ntypedef struct calc_noise_result_t {\n    FLOAT   over_noise;      /* sum of quantization noise > masking */\n    FLOAT   tot_noise;       /* sum of all quantization noise */\n    FLOAT   max_noise;       /* max quantization noise */\n    int     over_count;      /* number of quantization noise > masking */\n    int     over_SSD;        /* SSD-like cost of distorted bands */\n    int     bits;\n} calc_noise_result;\n\n\n/**\n* allows re-use of previously\n* computed noise values\n*/\ntypedef struct calc_noise_data_t {\n    int     global_gain;\n    int     sfb_count1;\n    int     step[39];\n    FLOAT   noise[39];\n    FLOAT   noise_log[39];\n} calc_noise_data;\n\n\nint     on_pe(lame_internal_flags * gfc, const FLOAT pe[2][2],\n              int targ_bits[2], int mean_bits, int gr, int cbr);\n\nvoid    reduce_side(int targ_bits[2], FLOAT ms_ener_ratio, int mean_bits, int max_bits);\n\n\nvoid    iteration_init(lame_internal_flags * gfc);\n\n\nint     calc_xmin(lame_internal_flags const *gfc,\n                  III_psy_ratio const *const ratio, gr_info * const cod_info, FLOAT * l3_xmin);\n\nint     calc_noise(const gr_info * const cod_info,\n                   const FLOAT * l3_xmin,\n                   FLOAT * distort, calc_noise_result * const res, calc_noise_data * prev_noise);\n\nvoid    set_frame_pinfo(lame_internal_flags * gfc, const III_psy_ratio ratio[2][2]);\n\n\n\n\n/* takehiro.c */\n\nint     count_bits(lame_internal_flags const *const gfc, const FLOAT * const xr,\n                   gr_info * const cod_info, calc_noise_data * prev_noise);\nint     noquant_count_bits(lame_internal_flags const *const gfc,\n                           gr_info * const cod_info, calc_noise_data * prev_noise);\n\n\nvoid    best_huffman_divide(const lame_internal_flags * const gfc, gr_info * const cod_info);\n\nvoid    best_scalefac_store(const lame_internal_flags * gfc, const int gr, const int ch,\n                            III_side_info_t * const l3_side);\n\nint     scale_bitcount(const lame_internal_flags * gfc, gr_info * cod_info);\n\nvoid    huffman_init(lame_internal_flags * const gfc);\n\nvoid    init_xrpow_core_init(lame_internal_flags * const gfc);\n\nFLOAT   athAdjust(FLOAT a, FLOAT x, FLOAT athFloor, float ATHfixpoint);\n\n#define LARGE_BITS 100000\n\n#endif /* LAME_QUANTIZE_PVT_H */\n"
  },
  {
    "path": "app/jni/libmp3lame/reservoir.c",
    "content": "/*\n *      bit reservoir source file\n *\n *      Copyright (c) 1999-2000 Mark Taylor\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: reservoir.c,v 1.45 2011/05/07 16:05:17 rbrito Exp $ */\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"reservoir.h\"\n\n#include \"bitstream.h\"\n#include \"lame-analysis.h\"\n#include \"lame_global_flags.h\"\n\n\n/*\n  ResvFrameBegin:\n  Called (repeatedly) at the beginning of a frame. Updates the maximum\n  size of the reservoir, and checks to make sure main_data_begin\n  was set properly by the formatter\n*/\n\n/*\n *  Background information:\n *\n *  This is the original text from the ISO standard. Because of\n *  sooo many bugs and irritations correcting comments are added\n *  in brackets []. A '^W' means you should remove the last word.\n *\n *  1) The following rule can be used to calculate the maximum\n *     number of bits used for one granule [^W frame]:\n *     At the highest possible bitrate of Layer III (320 kbps\n *     per stereo signal [^W^W^W], 48 kHz) the frames must be of\n *     [^W^W^W are designed to have] constant length, i.e.\n *     one buffer [^W^W the frame] length is:\n *\n *         320 kbps * 1152/48 kHz = 7680 bit = 960 byte\n *\n *     This value is used as the maximum buffer per channel [^W^W] at\n *     lower bitrates [than 320 kbps]. At 64 kbps mono or 128 kbps\n *     stereo the main granule length is 64 kbps * 576/48 kHz = 768 bit\n *     [per granule and channel] at 48 kHz sampling frequency.\n *     This means that there is a maximum deviation (short time buffer\n *     [= reservoir]) of 7680 - 2*2*768 = 4608 bits is allowed at 64 kbps.\n *     The actual deviation is equal to the number of bytes [with the\n *     meaning of octets] denoted by the main_data_end offset pointer.\n *     The actual maximum deviation is (2^9-1)*8 bit = 4088 bits\n *     [for MPEG-1 and (2^8-1)*8 bit for MPEG-2, both are hard limits].\n *     ... The xchange of buffer bits between the left and right channel\n *     is allowed without restrictions [exception: dual channel].\n *     Because of the [constructed] constraint on the buffer size\n *     main_data_end is always set to 0 in the case of bit_rate_index==14,\n *     i.e. data rate 320 kbps per stereo signal [^W^W^W]. In this case\n *     all data are allocated between adjacent header [^W sync] words\n *     [, i.e. there is no buffering at all].\n */\n\nint\nResvFrameBegin(lame_internal_flags * gfc, int *mean_bits)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    int     fullFrameBits;\n    int     resvLimit;\n    int     maxmp3buf;\n    III_side_info_t *const l3_side = &gfc->l3_side;\n    int     frameLength;\n    int     meanBits;\n\n    frameLength = getframebits(gfc);\n    meanBits = (frameLength - cfg->sideinfo_len * 8) / cfg->mode_gr;\n\n/*\n *  Meaning of the variables:\n *      resvLimit: (0, 8, ..., 8*255 (MPEG-2), 8*511 (MPEG-1))\n *          Number of bits can be stored in previous frame(s) due to\n *          counter size constaints\n *      maxmp3buf: ( ??? ... 8*1951 (MPEG-1 and 2), 8*2047 (MPEG-2.5))\n *          Number of bits allowed to encode one frame (you can take 8*511 bit\n *          from the bit reservoir and at most 8*1440 bit from the current\n *          frame (320 kbps, 32 kHz), so 8*1951 bit is the largest possible\n *          value for MPEG-1 and -2)\n *\n *          maximum allowed granule/channel size times 4 = 8*2047 bits.,\n *          so this is the absolute maximum supported by the format.\n *\n *\n *      fullFrameBits:  maximum number of bits available for encoding\n *                      the current frame.\n *\n *      mean_bits:      target number of bits per granule.\n *\n *      frameLength:\n *\n *      gfc->ResvMax:   maximum allowed reservoir\n *\n *      gfc->ResvSize:  current reservoir size\n *\n *      l3_side->resvDrain_pre:\n *         ancillary data to be added to previous frame:\n *         (only usefull in VBR modes if it is possible to have\n *         maxmp3buf < fullFrameBits)).  Currently disabled,\n *         see #define NEW_DRAIN\n *         2010-02-13: RH now enabled, it seems to be needed for CBR too,\n *                     as there exists one example, where the FhG decoder\n *                     can't decode a -b320 CBR file anymore.\n *\n *      l3_side->resvDrain_post:\n *         ancillary data to be added to this frame:\n *\n */\n\n    /* main_data_begin has 9 bits in MPEG-1, 8 bits MPEG-2 */\n    resvLimit = (8 * 256) * cfg->mode_gr - 8;\n\n    /* maximum allowed frame size.  dont use more than this number of\n       bits, even if the frame has the space for them: */\n    maxmp3buf = cfg->buffer_constraint;\n    esv->ResvMax = maxmp3buf - frameLength;\n    if (esv->ResvMax > resvLimit)\n        esv->ResvMax = resvLimit;\n    if (esv->ResvMax < 0 || cfg->disable_reservoir)\n        esv->ResvMax = 0;\n    \n    fullFrameBits = meanBits * cfg->mode_gr + Min(esv->ResvSize, esv->ResvMax);\n\n    if (fullFrameBits > maxmp3buf)\n        fullFrameBits = maxmp3buf;\n\n    assert(0 == esv->ResvMax % 8);\n    assert(esv->ResvMax >= 0);\n\n    l3_side->resvDrain_pre = 0;\n\n    if (gfc->pinfo != NULL) {\n        gfc->pinfo->mean_bits = meanBits / 2; /* expected bits per channel per granule [is this also right for mono/stereo, MPEG-1/2 ?] */\n        gfc->pinfo->resvsize = esv->ResvSize;\n    }\n    *mean_bits = meanBits;\n    return fullFrameBits;\n}\n\n\n/*\n  ResvMaxBits\n  returns targ_bits:  target number of bits to use for 1 granule\n         extra_bits:  amount extra available from reservoir\n  Mark Taylor 4/99\n*/\nvoid\nResvMaxBits(lame_internal_flags * gfc, int mean_bits, int *targ_bits, int *extra_bits, int cbr)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    int     add_bits, targBits, extraBits;\n    int     ResvSize = esv->ResvSize, ResvMax = esv->ResvMax;\n\n    /* conpensate the saved bits used in the 1st granule */\n    if (cbr)\n        ResvSize += mean_bits;\n\n    if (gfc->sv_qnt.substep_shaping & 1)\n        ResvMax *= 0.9;\n\n    targBits = mean_bits;\n\n    /* extra bits if the reservoir is almost full */\n    if (ResvSize * 10 > ResvMax * 9) {\n        add_bits = ResvSize - (ResvMax * 9) / 10;\n        targBits += add_bits;\n        gfc->sv_qnt.substep_shaping |= 0x80;\n    }\n    else {\n        add_bits = 0;\n        gfc->sv_qnt.substep_shaping &= 0x7f;\n        /* build up reservoir.  this builds the reservoir a little slower\n         * than FhG.  It could simple be mean_bits/15, but this was rigged\n         * to always produce 100 (the old value) at 128kbs */\n        /*    *targ_bits -= (int) (mean_bits/15.2); */\n        if (!cfg->disable_reservoir && !(gfc->sv_qnt.substep_shaping & 1))\n            targBits -= .1 * mean_bits;\n    }\n\n\n    /* amount from the reservoir we are allowed to use. ISO says 6/10 */\n    extraBits = (ResvSize < (esv->ResvMax * 6) / 10 ? ResvSize : (esv->ResvMax * 6) / 10);\n    extraBits -= add_bits;\n\n    if (extraBits < 0)\n        extraBits = 0;\n\n    *targ_bits = targBits;\n    *extra_bits = extraBits;\n}\n\n/*\n  ResvAdjust:\n  Called after a granule's bit allocation. Readjusts the size of\n  the reservoir to reflect the granule's usage.\n*/\nvoid\nResvAdjust(lame_internal_flags * gfc, gr_info const *gi)\n{\n    gfc->sv_enc.ResvSize -= gi->part2_3_length + gi->part2_length;\n}\n\n\n/*\n  ResvFrameEnd:\n  Called after all granules in a frame have been allocated. Makes sure\n  that the reservoir size is within limits, possibly by adding stuffing\n  bits.\n*/\nvoid\nResvFrameEnd(lame_internal_flags * gfc, int mean_bits)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncStateVar_t *const esv = &gfc->sv_enc;\n    III_side_info_t *const l3_side = &gfc->l3_side;\n    int     stuffingBits;\n    int     over_bits;\n\n    esv->ResvSize += mean_bits * cfg->mode_gr;\n    stuffingBits = 0;\n    l3_side->resvDrain_post = 0;\n    l3_side->resvDrain_pre = 0;\n\n    /* we must be byte aligned */\n    if ((over_bits = esv->ResvSize % 8) != 0)\n        stuffingBits += over_bits;\n\n\n    over_bits = (esv->ResvSize - stuffingBits) - esv->ResvMax;\n    if (over_bits > 0) {\n        assert(0 == over_bits % 8);\n        assert(over_bits >= 0);\n        stuffingBits += over_bits;\n    }\n\n\n    /* NOTE: enabling the NEW_DRAIN code fixes some problems with FhG decoder\n             shipped with MS Windows operating systems. Using this, it is even\n             possible to use Gabriel's lax buffer consideration again, which\n             assumes, any decoder should have a buffer large enough\n             for a 320 kbps frame at 32 kHz sample rate.\n\n       old drain code:\n             lame -b320 BlackBird.wav ---> does not play with GraphEdit.exe using FhG decoder V1.5 Build 50\n\n       new drain code:\n             lame -b320 BlackBird.wav ---> plays fine with GraphEdit.exe using FhG decoder V1.5 Build 50\n\n             Robert Hegemann, 2010-02-13.\n     */\n    /* drain as many bits as possible into previous frame ancillary data\n     * In particular, in VBR mode ResvMax may have changed, and we have\n     * to make sure main_data_begin does not create a reservoir bigger\n     * than ResvMax  mt 4/00*/\n    {\n        int     mdb_bytes = Min(l3_side->main_data_begin * 8, stuffingBits) / 8;\n        l3_side->resvDrain_pre += 8 * mdb_bytes;\n        stuffingBits -= 8 * mdb_bytes;\n        esv->ResvSize -= 8 * mdb_bytes;\n        l3_side->main_data_begin -= mdb_bytes;\n    }\n    /* drain the rest into this frames ancillary data */\n    l3_side->resvDrain_post += stuffingBits;\n    esv->ResvSize -= stuffingBits;\n}\n"
  },
  {
    "path": "app/jni/libmp3lame/reservoir.h",
    "content": "/*\n *\tbit reservoir include file\n *\n *\tCopyright (c) 1999 Mark Taylor\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_RESERVOIR_H\n#define LAME_RESERVOIR_H\n\nint     ResvFrameBegin(lame_internal_flags * gfc, int *mean_bits);\nvoid    ResvMaxBits(lame_internal_flags * gfc, int mean_bits, int *targ_bits, int *max_bits,\n                    int cbr);\nvoid    ResvAdjust(lame_internal_flags * gfc, gr_info const *gi);\nvoid    ResvFrameEnd(lame_internal_flags * gfc, int mean_bits);\n\n#endif /* LAME_RESERVOIR_H */\n"
  },
  {
    "path": "app/jni/libmp3lame/set_get.c",
    "content": "/* -*- mode: C; mode: fold -*- */\n/*\n * set/get functions for lame_global_flags\n *\n * Copyright (c) 2001-2005 Alexander Leidinger\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: set_get.c,v 1.98 2011/05/07 16:05:17 rbrito Exp $ */\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"bitstream.h\"  /* because of compute_flushbits */\n\n#include \"set_get.h\"\n#include \"lame_global_flags.h\"\n\n/*\n * input stream description\n */\n\n\n/* number of samples */\n/* it's unlikely for this function to return an error */\nint\nlame_set_num_samples(lame_global_flags * gfp, unsigned long num_samples)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 2^32-1 */\n        gfp->num_samples = num_samples;\n        return 0;\n    }\n    return -1;\n}\n\nunsigned long\nlame_get_num_samples(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->num_samples;\n    }\n    return 0;\n}\n\n\n/* input samplerate */\nint\nlame_set_in_samplerate(lame_global_flags * gfp, int in_samplerate)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* input sample rate in Hz,  default = 44100 Hz */\n        gfp->samplerate_in = in_samplerate;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_in_samplerate(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->samplerate_in;\n    }\n    return 0;\n}\n\n\n/* number of channels in input stream */\nint\nlame_set_num_channels(lame_global_flags * gfp, int num_channels)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 2 */\n        if (2 < num_channels || 0 == num_channels) {\n            return -1;  /* we don't support more than 2 channels */\n        }\n        gfp->num_channels = num_channels;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_num_channels(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->num_channels;\n    }\n    return 0;\n}\n\n\n/* scale the input by this amount before encoding (not used for decoding) */\nint\nlame_set_scale(lame_global_flags * gfp, float scale)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 1 */\n        gfp->scale = scale;\n        return 0;\n    }\n    return -1;\n}\n\nfloat\nlame_get_scale(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->scale;\n    }\n    return 0;\n}\n\n\n/* scale the channel 0 (left) input by this amount before \n   encoding (not used for decoding) */\nint\nlame_set_scale_left(lame_global_flags * gfp, float scale)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 1 */\n        gfp->scale_left = scale;\n        return 0;\n    }\n    return -1;\n}\n\nfloat\nlame_get_scale_left(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->scale_left;\n    }\n    return 0;\n}\n\n\n/* scale the channel 1 (right) input by this amount before \n   encoding (not used for decoding) */\nint\nlame_set_scale_right(lame_global_flags * gfp, float scale)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 1 */\n        gfp->scale_right = scale;\n        return 0;\n    }\n    return -1;\n}\n\nfloat\nlame_get_scale_right(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->scale_right;\n    }\n    return 0;\n}\n\n\n/* output sample rate in Hz */\nint\nlame_set_out_samplerate(lame_global_flags * gfp, int out_samplerate)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /*\n         * default = 0: LAME picks best value based on the amount\n         *              of compression\n         * MPEG only allows:\n         *  MPEG1    32, 44.1,   48khz\n         *  MPEG2    16, 22.05,  24\n         *  MPEG2.5   8, 11.025, 12\n         *\n         * (not used by decoding routines)\n         */\n        gfp->samplerate_out = out_samplerate;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_out_samplerate(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->samplerate_out;\n    }\n    return 0;\n}\n\n\n\n\n/*\n * general control parameters\n */\n\n/* collect data for an MP3 frame analzyer */\nint\nlame_set_analysis(lame_global_flags * gfp, int analysis)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > analysis || 1 < analysis)\n            return -1;\n        gfp->analysis = analysis;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_analysis(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->analysis && 1 >= gfp->analysis);\n        return gfp->analysis;\n    }\n    return 0;\n}\n\n\n/* write a Xing VBR header frame */\nint\nlame_set_bWriteVbrTag(lame_global_flags * gfp, int bWriteVbrTag)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 1 (on) for VBR/ABR modes, 0 (off) for CBR mode */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > bWriteVbrTag || 1 < bWriteVbrTag)\n            return -1;\n        gfp->write_lame_tag = bWriteVbrTag;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_bWriteVbrTag(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->write_lame_tag && 1 >= gfp->write_lame_tag);\n        return gfp->write_lame_tag;\n    }\n    return 0;\n}\n\n\n\n/* decode only, use lame/mpglib to convert mp3 to wav */\nint\nlame_set_decode_only(lame_global_flags * gfp, int decode_only)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 (disabled) */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > decode_only || 1 < decode_only)\n            return -1;\n        gfp->decode_only = decode_only;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_decode_only(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->decode_only && 1 >= gfp->decode_only);\n        return gfp->decode_only;\n    }\n    return 0;\n}\n\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n/* 1=encode a Vorbis .ogg file.  default=0 */\n/* DEPRECATED */\nint CDECL lame_set_ogg(lame_global_flags *, int);\nint CDECL lame_get_ogg(const lame_global_flags *);\n#else\n#endif\n\n/* encode a Vorbis .ogg file */\n/* DEPRECATED */\nint\nlame_set_ogg(lame_global_flags * gfp, int ogg)\n{\n    (void) gfp;\n    (void) ogg;\n    return -1;\n}\n\nint\nlame_get_ogg(const lame_global_flags * gfp)\n{\n    (void) gfp;\n    return 0;\n}\n\n\n/*\n * Internal algorithm selection.\n * True quality is determined by the bitrate but this variable will effect\n * quality by selecting expensive or cheap algorithms.\n * quality=0..9.  0=best (very slow).  9=worst.  \n * recommended:  3     near-best quality, not too slow\n *               5     good quality, fast\n *               7     ok quality, really fast\n */\nint\nlame_set_quality(lame_global_flags * gfp, int quality)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        if (quality < 0) {\n            gfp->quality = 0;\n        }\n        else if (quality > 9) {\n            gfp->quality = 9;\n        }\n        else {\n            gfp->quality = quality;\n        }\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_quality(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->quality;\n    }\n    return 0;\n}\n\n\n/* mode = STEREO, JOINT_STEREO, DUAL_CHANNEL (not supported), MONO */\nint\nlame_set_mode(lame_global_flags * gfp, MPEG_mode mode)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        int     mpg_mode = mode;\n        /* default: lame chooses based on compression ratio and input channels */\n        if (mpg_mode < 0 || MAX_INDICATOR <= mpg_mode)\n            return -1;  /* Unknown MPEG mode! */\n        gfp->mode = mode;\n        return 0;\n    }\n    return -1;\n}\n\nMPEG_mode\nlame_get_mode(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(gfp->mode < MAX_INDICATOR);\n        return gfp->mode;\n    }\n    return NOT_SET;\n}\n\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n/*\n  mode_automs.  Use a M/S mode with a switching threshold based on\n  compression ratio\n  DEPRECATED\n*/\nint CDECL lame_set_mode_automs(lame_global_flags *, int);\nint CDECL lame_get_mode_automs(const lame_global_flags *);\n#else\n#endif\n\n/* Us a M/S mode with a switching threshold based on compression ratio */\n/* DEPRECATED */\nint\nlame_set_mode_automs(lame_global_flags * gfp, int mode_automs)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 (disabled) */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > mode_automs || 1 < mode_automs)\n            return -1;\n        lame_set_mode(gfp, JOINT_STEREO);\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_mode_automs(const lame_global_flags * gfp)\n{\n    (void) gfp;\n    return 1;\n}\n\n\n/*\n * Force M/S for all frames.  For testing only.\n * Requires mode = 1.\n */\nint\nlame_set_force_ms(lame_global_flags * gfp, int force_ms)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 (disabled) */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > force_ms || 1 < force_ms)\n            return -1;\n        gfp->force_ms = force_ms;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_force_ms(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->force_ms && 1 >= gfp->force_ms);\n        return gfp->force_ms;\n    }\n    return 0;\n}\n\n\n/* Use free_format. */\nint\nlame_set_free_format(lame_global_flags * gfp, int free_format)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 (disabled) */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > free_format || 1 < free_format)\n            return -1;\n        gfp->free_format = free_format;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_free_format(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->free_format && 1 >= gfp->free_format);\n        return gfp->free_format;\n    }\n    return 0;\n}\n\n\n\n/* Perform ReplayGain analysis */\nint\nlame_set_findReplayGain(lame_global_flags * gfp, int findReplayGain)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 (disabled) */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > findReplayGain || 1 < findReplayGain)\n            return -1;\n        gfp->findReplayGain = findReplayGain;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_findReplayGain(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->findReplayGain && 1 >= gfp->findReplayGain);\n        return gfp->findReplayGain;\n    }\n    return 0;\n}\n\n\n/* Decode on the fly. Find the peak sample. If ReplayGain analysis is \n   enabled then perform it on the decoded data. */\nint\nlame_set_decode_on_the_fly(lame_global_flags * gfp, int decode_on_the_fly)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n#ifndef DECODE_ON_THE_FLY\n        return -1;\n#else\n        /* default = 0 (disabled) */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > decode_on_the_fly || 1 < decode_on_the_fly)\n            return -1;\n\n        gfp->decode_on_the_fly = decode_on_the_fly;\n\n        return 0;\n#endif\n    }\n    return -1;\n}\n\nint\nlame_get_decode_on_the_fly(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->decode_on_the_fly && 1 >= gfp->decode_on_the_fly);\n        return gfp->decode_on_the_fly;\n    }\n    return 0;\n}\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n/* DEPRECATED: now does the same as lame_set_findReplayGain()\n   default = 0 (disabled) */\nint CDECL lame_set_ReplayGain_input(lame_global_flags *, int);\nint CDECL lame_get_ReplayGain_input(const lame_global_flags *);\n\n/* DEPRECATED: now does the same as\n   lame_set_decode_on_the_fly() && lame_set_findReplayGain()\n   default = 0 (disabled) */\nint CDECL lame_set_ReplayGain_decode(lame_global_flags *, int);\nint CDECL lame_get_ReplayGain_decode(const lame_global_flags *);\n\n/* DEPRECATED: now does the same as lame_set_decode_on_the_fly()\n   default = 0 (disabled) */\nint CDECL lame_set_findPeakSample(lame_global_flags *, int);\nint CDECL lame_get_findPeakSample(const lame_global_flags *);\n#else\n#endif\n\n/* DEPRECATED. same as lame_set_decode_on_the_fly() */\nint\nlame_set_findPeakSample(lame_global_flags * gfp, int arg)\n{\n    return lame_set_decode_on_the_fly(gfp, arg);\n}\n\nint\nlame_get_findPeakSample(const lame_global_flags * gfp)\n{\n    return lame_get_decode_on_the_fly(gfp);\n}\n\n/* DEPRECATED. same as lame_set_findReplayGain() */\nint\nlame_set_ReplayGain_input(lame_global_flags * gfp, int arg)\n{\n    return lame_set_findReplayGain(gfp, arg);\n}\n\nint\nlame_get_ReplayGain_input(const lame_global_flags * gfp)\n{\n    return lame_get_findReplayGain(gfp);\n}\n\n/* DEPRECATED. same as lame_set_decode_on_the_fly() &&\n   lame_set_findReplayGain() */\nint\nlame_set_ReplayGain_decode(lame_global_flags * gfp, int arg)\n{\n    if (lame_set_decode_on_the_fly(gfp, arg) < 0 || lame_set_findReplayGain(gfp, arg) < 0)\n        return -1;\n    else\n        return 0;\n}\n\nint\nlame_get_ReplayGain_decode(const lame_global_flags * gfp)\n{\n    if (lame_get_decode_on_the_fly(gfp) > 0 && lame_get_findReplayGain(gfp) > 0)\n        return 1;\n    else\n        return 0;\n}\n\n\n/* set and get some gapless encoding flags */\n\nint\nlame_set_nogap_total(lame_global_flags * gfp, int the_nogap_total)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->nogap_total = the_nogap_total;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_nogap_total(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->nogap_total;\n    }\n    return 0;\n}\n\nint\nlame_set_nogap_currentindex(lame_global_flags * gfp, int the_nogap_index)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->nogap_current = the_nogap_index;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_nogap_currentindex(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->nogap_current;\n    }\n    return 0;\n}\n\n\n/* message handlers */\nint\nlame_set_errorf(lame_global_flags * gfp, void (*func) (const char *, va_list))\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->report.errorf = func;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_set_debugf(lame_global_flags * gfp, void (*func) (const char *, va_list))\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->report.debugf = func;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_set_msgf(lame_global_flags * gfp, void (*func) (const char *, va_list))\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->report.msgf = func;\n        return 0;\n    }\n    return -1;\n}\n\n\n/*\n * Set one of\n *  - brate\n *  - compression ratio.\n *\n * Default is compression ratio of 11.\n */\nint\nlame_set_brate(lame_global_flags * gfp, int brate)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->brate = brate;\n        if (brate > 320) {\n            gfp->disable_reservoir = 1;\n        }\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_brate(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->brate;\n    }\n    return 0;\n}\n\nint\nlame_set_compression_ratio(lame_global_flags * gfp, float compression_ratio)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->compression_ratio = compression_ratio;\n        return 0;\n    }\n    return -1;\n}\n\nfloat\nlame_get_compression_ratio(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->compression_ratio;\n    }\n    return 0;\n}\n\n\n\n\n/*\n * frame parameters\n */\n\n/* Mark as copyright protected. */\nint\nlame_set_copyright(lame_global_flags * gfp, int copyright)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 (disabled) */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > copyright || 1 < copyright)\n            return -1;\n        gfp->copyright = copyright;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_copyright(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->copyright && 1 >= gfp->copyright);\n        return gfp->copyright;\n    }\n    return 0;\n}\n\n\n/* Mark as original. */\nint\nlame_set_original(lame_global_flags * gfp, int original)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 1 (enabled) */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > original || 1 < original)\n            return -1;\n        gfp->original = original;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_original(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->original && 1 >= gfp->original);\n        return gfp->original;\n    }\n    return 0;\n}\n\n\n/*\n * error_protection.\n * Use 2 bytes from each frame for CRC checksum.\n */\nint\nlame_set_error_protection(lame_global_flags * gfp, int error_protection)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 (disabled) */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > error_protection || 1 < error_protection)\n            return -1;\n        gfp->error_protection = error_protection;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_error_protection(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->error_protection && 1 >= gfp->error_protection);\n        return gfp->error_protection;\n    }\n    return 0;\n}\n\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\n/* padding_type. 0=pad no frames  1=pad all frames 2=adjust padding(default) */\nint CDECL lame_set_padding_type(lame_global_flags *, Padding_type);\nPadding_type CDECL lame_get_padding_type(const lame_global_flags *);\n#else\n#endif\n\n/*\n * padding_type.\n *  PAD_NO     = pad no frames\n *  PAD_ALL    = pad all frames\n *  PAD_ADJUST = adjust padding\n */\nint\nlame_set_padding_type(lame_global_flags * gfp, Padding_type padding_type)\n{\n    (void) gfp;\n    (void) padding_type;\n    return 0;\n}\n\nPadding_type\nlame_get_padding_type(const lame_global_flags * gfp)\n{\n    (void) gfp;\n    return PAD_ADJUST;\n}\n\n\n/* MP3 'private extension' bit. Meaningless. */\nint\nlame_set_extension(lame_global_flags * gfp, int extension)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 (disabled) */\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > extension || 1 < extension)\n            return -1;\n        gfp->extension = extension;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_extension(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->extension && 1 >= gfp->extension);\n        return gfp->extension;\n    }\n    return 0;\n}\n\n\n/* Enforce strict ISO compliance. */\nint\nlame_set_strict_ISO(lame_global_flags * gfp, int val)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 (disabled) */\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (val < MDB_DEFAULT || MDB_MAXIMUM < val)\n            return -1;\n        gfp->strict_ISO = val;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_strict_ISO(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->strict_ISO;\n    }\n    return 0;\n}\n\n\n\n\n/********************************************************************\n * quantization/noise shaping \n ***********************************************************************/\n\n/* Disable the bit reservoir. For testing only. */\nint\nlame_set_disable_reservoir(lame_global_flags * gfp, int disable_reservoir)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 (disabled) */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > disable_reservoir || 1 < disable_reservoir)\n            return -1;\n        gfp->disable_reservoir = disable_reservoir;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_disable_reservoir(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->disable_reservoir && 1 >= gfp->disable_reservoir);\n        return gfp->disable_reservoir;\n    }\n    return 0;\n}\n\n\n\n\nint\nlame_set_experimentalX(lame_global_flags * gfp, int experimentalX)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_set_quant_comp(gfp, experimentalX);\n        lame_set_quant_comp_short(gfp, experimentalX);\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_experimentalX(const lame_global_flags * gfp)\n{\n    return lame_get_quant_comp(gfp);\n}\n\n\n/* Select a different \"best quantization\" function. default = 0 */\nint\nlame_set_quant_comp(lame_global_flags * gfp, int quant_type)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->quant_comp = quant_type;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_quant_comp(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->quant_comp;\n    }\n    return 0;\n}\n\n\n/* Select a different \"best quantization\" function. default = 0 */\nint\nlame_set_quant_comp_short(lame_global_flags * gfp, int quant_type)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->quant_comp_short = quant_type;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_quant_comp_short(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->quant_comp_short;\n    }\n    return 0;\n}\n\n\n/* Another experimental option. For testing only. */\nint\nlame_set_experimentalY(lame_global_flags * gfp, int experimentalY)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->experimentalY = experimentalY;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_experimentalY(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->experimentalY;\n    }\n    return 0;\n}\n\n\nint\nlame_set_experimentalZ(lame_global_flags * gfp, int experimentalZ)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->experimentalZ = experimentalZ;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_experimentalZ(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->experimentalZ;\n    }\n    return 0;\n}\n\n\n/* Naoki's psycho acoustic model. */\nint\nlame_set_exp_nspsytune(lame_global_flags * gfp, int exp_nspsytune)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 (disabled) */\n        gfp->exp_nspsytune = exp_nspsytune;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_exp_nspsytune(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->exp_nspsytune;\n    }\n    return 0;\n}\n\n\n\n\n/********************************************************************\n * VBR control\n ***********************************************************************/\n\n/* Types of VBR.  default = vbr_off = CBR */\nint\nlame_set_VBR(lame_global_flags * gfp, vbr_mode VBR)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        int     vbr_q = VBR;\n        if (0 > vbr_q || vbr_max_indicator <= vbr_q)\n            return -1;  /* Unknown VBR mode! */\n        gfp->VBR = VBR;\n        return 0;\n    }\n    return -1;\n}\n\nvbr_mode\nlame_get_VBR(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(gfp->VBR < vbr_max_indicator);\n        return gfp->VBR;\n    }\n    return vbr_off;\n}\n\n\n/*\n * VBR quality level.\n *  0 = highest\n *  9 = lowest \n */\nint\nlame_set_VBR_q(lame_global_flags * gfp, int VBR_q)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        int     ret = 0;\n\n        if (0 > VBR_q) {\n            ret = -1;   /* Unknown VBR quality level! */\n            VBR_q = 0;\n        }\n        if (9 < VBR_q) {\n            ret = -1;\n            VBR_q = 9;\n        }\n        gfp->VBR_q = VBR_q;\n        gfp->VBR_q_frac = 0;\n        return ret;\n    }\n    return -1;\n}\n\nint\nlame_get_VBR_q(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->VBR_q && 10 > gfp->VBR_q);\n        return gfp->VBR_q;\n    }\n    return 0;\n}\n\nint\nlame_set_VBR_quality(lame_global_flags * gfp, float VBR_q)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        int     ret = 0;\n\n        if (0 > VBR_q) {\n            ret = -1;   /* Unknown VBR quality level! */\n            VBR_q = 0;\n        }\n        if (9.999 < VBR_q) {\n            ret = -1;\n            VBR_q = 9.999;\n        }\n\n        gfp->VBR_q = (int) VBR_q;\n        gfp->VBR_q_frac = VBR_q - gfp->VBR_q;\n\n        return ret;\n    }\n    return -1;\n}\n\nfloat\nlame_get_VBR_quality(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->VBR_q + gfp->VBR_q_frac;\n    }\n    return 0;\n}\n\n\n/* Ignored except for VBR = vbr_abr (ABR mode) */\nint\nlame_set_VBR_mean_bitrate_kbps(lame_global_flags * gfp, int VBR_mean_bitrate_kbps)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->VBR_mean_bitrate_kbps = VBR_mean_bitrate_kbps;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_VBR_mean_bitrate_kbps(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->VBR_mean_bitrate_kbps;\n    }\n    return 0;\n}\n\nint\nlame_set_VBR_min_bitrate_kbps(lame_global_flags * gfp, int VBR_min_bitrate_kbps)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->VBR_min_bitrate_kbps = VBR_min_bitrate_kbps;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_VBR_min_bitrate_kbps(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->VBR_min_bitrate_kbps;\n    }\n    return 0;\n}\n\nint\nlame_set_VBR_max_bitrate_kbps(lame_global_flags * gfp, int VBR_max_bitrate_kbps)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->VBR_max_bitrate_kbps = VBR_max_bitrate_kbps;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_VBR_max_bitrate_kbps(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->VBR_max_bitrate_kbps;\n    }\n    return 0;\n}\n\n\n/*\n * Strictly enforce VBR_min_bitrate.\n * Normally it will be violated for analog silence.\n */\nint\nlame_set_VBR_hard_min(lame_global_flags * gfp, int VBR_hard_min)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 (disabled) */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > VBR_hard_min || 1 < VBR_hard_min)\n            return -1;\n\n        gfp->VBR_hard_min = VBR_hard_min;\n\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_VBR_hard_min(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->VBR_hard_min && 1 >= gfp->VBR_hard_min);\n        return gfp->VBR_hard_min;\n    }\n    return 0;\n}\n\n\n/********************************************************************\n * Filtering control\n ***********************************************************************/\n\n/*\n * Freqency in Hz to apply lowpass.\n *   0 = default = lame chooses\n *  -1 = disabled\n */\nint\nlame_set_lowpassfreq(lame_global_flags * gfp, int lowpassfreq)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->lowpassfreq = lowpassfreq;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_lowpassfreq(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->lowpassfreq;\n    }\n    return 0;\n}\n\n\n/*\n * Width of transition band (in Hz).\n *  default = one polyphase filter band\n */\nint\nlame_set_lowpasswidth(lame_global_flags * gfp, int lowpasswidth)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->lowpasswidth = lowpasswidth;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_lowpasswidth(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->lowpasswidth;\n    }\n    return 0;\n}\n\n\n/*\n * Frequency in Hz to apply highpass.\n *   0 = default = lame chooses\n *  -1 = disabled\n */\nint\nlame_set_highpassfreq(lame_global_flags * gfp, int highpassfreq)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->highpassfreq = highpassfreq;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_highpassfreq(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->highpassfreq;\n    }\n    return 0;\n}\n\n\n/*\n * Width of transition band (in Hz).\n *  default = one polyphase filter band\n */\nint\nlame_set_highpasswidth(lame_global_flags * gfp, int highpasswidth)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->highpasswidth = highpasswidth;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_highpasswidth(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->highpasswidth;\n    }\n    return 0;\n}\n\n\n\n\n/*\n * psycho acoustics and other arguments which you should not change \n * unless you know what you are doing\n */\n\n\n/* Adjust masking values. */\nint\nlame_set_maskingadjust(lame_global_flags * gfp, float adjust)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->maskingadjust = adjust;\n        return 0;\n    }\n    return -1;\n}\n\nfloat\nlame_get_maskingadjust(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->maskingadjust;\n    }\n    return 0;\n}\n\nint\nlame_set_maskingadjust_short(lame_global_flags * gfp, float adjust)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->maskingadjust_short = adjust;\n        return 0;\n    }\n    return -1;\n}\n\nfloat\nlame_get_maskingadjust_short(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->maskingadjust_short;\n    }\n    return 0;\n}\n\n/* Only use ATH for masking. */\nint\nlame_set_ATHonly(lame_global_flags * gfp, int ATHonly)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->ATHonly = ATHonly;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_ATHonly(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->ATHonly;\n    }\n    return 0;\n}\n\n\n/* Only use ATH for short blocks. */\nint\nlame_set_ATHshort(lame_global_flags * gfp, int ATHshort)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->ATHshort = ATHshort;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_ATHshort(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->ATHshort;\n    }\n    return 0;\n}\n\n\n/* Disable ATH. */\nint\nlame_set_noATH(lame_global_flags * gfp, int noATH)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->noATH = noATH;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_noATH(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->noATH;\n    }\n    return 0;\n}\n\n\n/* Select ATH formula. */\nint\nlame_set_ATHtype(lame_global_flags * gfp, int ATHtype)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* XXX: ATHtype should be converted to an enum. */\n        gfp->ATHtype = ATHtype;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_ATHtype(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->ATHtype;\n    }\n    return 0;\n}\n\n\n/* Select ATH formula 4 shape. */\nint\nlame_set_ATHcurve(lame_global_flags * gfp, float ATHcurve)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->ATHcurve = ATHcurve;\n        return 0;\n    }\n    return -1;\n}\n\nfloat\nlame_get_ATHcurve(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->ATHcurve;\n    }\n    return 0;\n}\n\n\n/* Lower ATH by this many db. */\nint\nlame_set_ATHlower(lame_global_flags * gfp, float ATHlower)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->ATH_lower_db = ATHlower;\n        return 0;\n    }\n    return -1;\n}\n\nfloat\nlame_get_ATHlower(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->ATH_lower_db;\n    }\n    return 0;\n}\n\n\n/* Select ATH adaptive adjustment scheme. */\nint\nlame_set_athaa_type(lame_global_flags * gfp, int athaa_type)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->athaa_type = athaa_type;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_athaa_type(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->athaa_type;\n    }\n    return 0;\n}\n\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\nint CDECL lame_set_athaa_loudapprox(lame_global_flags * gfp, int athaa_loudapprox);\nint CDECL lame_get_athaa_loudapprox(const lame_global_flags * gfp);\n#else\n#endif\n\n/* Select the loudness approximation used by the ATH adaptive auto-leveling. */\nint\nlame_set_athaa_loudapprox(lame_global_flags * gfp, int athaa_loudapprox)\n{\n    (void) gfp;\n    (void) athaa_loudapprox;\n    return 0;\n}\n\nint\nlame_get_athaa_loudapprox(const lame_global_flags * gfp)\n{\n    (void) gfp;\n    /* obsolete, the type known under number 2 is the only survival */\n    return 2;\n}\n\n\n/* Adjust (in dB) the point below which adaptive ATH level adjustment occurs. */\nint\nlame_set_athaa_sensitivity(lame_global_flags * gfp, float athaa_sensitivity)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->athaa_sensitivity = athaa_sensitivity;\n        return 0;\n    }\n    return -1;\n}\n\nfloat\nlame_get_athaa_sensitivity(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->athaa_sensitivity;\n    }\n    return 0;\n}\n\n\n/* Predictability limit (ISO tonality formula) */\nint     lame_set_cwlimit(lame_global_flags * gfp, int cwlimit);\nint     lame_get_cwlimit(const lame_global_flags * gfp);\n\nint\nlame_set_cwlimit(lame_global_flags * gfp, int cwlimit)\n{\n    (void) gfp;\n    (void) cwlimit;\n    return 0;\n}\n\nint\nlame_get_cwlimit(const lame_global_flags * gfp)\n{\n    (void) gfp;\n    return 0;\n}\n\n\n\n/*\n * Allow blocktypes to differ between channels.\n * default:\n *  0 for jstereo => block types coupled\n *  1 for stereo  => block types may differ\n */\nint\nlame_set_allow_diff_short(lame_global_flags * gfp, int allow_diff_short)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->short_blocks = allow_diff_short ? short_block_allowed : short_block_coupled;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_allow_diff_short(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        if (gfp->short_blocks == short_block_allowed)\n            return 1;   /* short blocks allowed to differ */\n        else\n            return 0;   /* not set, dispensed, forced or coupled */\n    }\n    return 0;\n}\n\n\n/* Use temporal masking effect */\nint\nlame_set_useTemporal(lame_global_flags * gfp, int useTemporal)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 1 (enabled) */\n\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 <= useTemporal && useTemporal <= 1) {\n            gfp->useTemporal = useTemporal;\n            return 0;\n        }\n    }\n    return -1;\n}\n\nint\nlame_get_useTemporal(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->useTemporal && 1 >= gfp->useTemporal);\n        return gfp->useTemporal;\n    }\n    return 0;\n}\n\n\n/* Use inter-channel masking effect */\nint\nlame_set_interChRatio(lame_global_flags * gfp, float ratio)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0.0 (no inter-channel maskin) */\n        if (0 <= ratio && ratio <= 1.0) {\n            gfp->interChRatio = ratio;\n            return 0;\n        }\n    }\n    return -1;\n}\n\nfloat\nlame_get_interChRatio(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert((0 <= gfp->interChRatio && gfp->interChRatio <= 1.0) || EQ(gfp->interChRatio, -1));\n        return gfp->interChRatio;\n    }\n    return 0;\n}\n\n\n/* Use pseudo substep shaping method */\nint\nlame_set_substep(lame_global_flags * gfp, int method)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0.0 (no substep noise shaping) */\n        if (0 <= method && method <= 7) {\n            gfp->substep_shaping = method;\n            return 0;\n        }\n    }\n    return -1;\n}\n\nint\nlame_get_substep(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->substep_shaping && gfp->substep_shaping <= 7);\n        return gfp->substep_shaping;\n    }\n    return 0;\n}\n\n/* scalefactors scale */\nint\nlame_set_sfscale(lame_global_flags * gfp, int val)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->noise_shaping = (val != 0) ? 2 : 1;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_sfscale(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return (gfp->noise_shaping == 2) ? 1 : 0;\n    }\n    return 0;\n}\n\n/* subblock gain */\nint\nlame_set_subblock_gain(lame_global_flags * gfp, int sbgain)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->subblock_gain = sbgain;\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_subblock_gain(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->subblock_gain;\n    }\n    return 0;\n}\n\n\n/* Disable short blocks. */\nint\nlame_set_no_short_blocks(lame_global_flags * gfp, int no_short_blocks)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 <= no_short_blocks && no_short_blocks <= 1) {\n            gfp->short_blocks = no_short_blocks ? short_block_dispensed : short_block_allowed;\n            return 0;\n        }\n    }\n    return -1;\n}\n\nint\nlame_get_no_short_blocks(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        switch (gfp->short_blocks) {\n        default:\n        case short_block_not_set:\n            return -1;\n        case short_block_dispensed:\n            return 1;\n        case short_block_allowed:\n        case short_block_coupled:\n        case short_block_forced:\n            return 0;\n        }\n    }\n    return -1;\n}\n\n\n/* Force short blocks. */\nint\nlame_set_force_short_blocks(lame_global_flags * gfp, int short_blocks)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* enforce disable/enable meaning, if we need more than two values\n           we need to switch to an enum to have an apropriate representation\n           of the possible meanings of the value */\n        if (0 > short_blocks || 1 < short_blocks)\n            return -1;\n\n        if (short_blocks == 1)\n            gfp->short_blocks = short_block_forced;\n        else if (gfp->short_blocks == short_block_forced)\n            gfp->short_blocks = short_block_allowed;\n\n        return 0;\n    }\n    return -1;\n}\n\nint\nlame_get_force_short_blocks(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        switch (gfp->short_blocks) {\n        default:\n        case short_block_not_set:\n            return -1;\n        case short_block_dispensed:\n        case short_block_allowed:\n        case short_block_coupled:\n            return 0;\n        case short_block_forced:\n            return 1;\n        }\n    }\n    return -1;\n}\n\nint\nlame_set_short_threshold_lrm(lame_global_flags * gfp, float lrm)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->attackthre = lrm;\n        return 0;\n    }\n    return -1;\n}\n\nfloat\nlame_get_short_threshold_lrm(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->attackthre;\n    }\n    return 0;\n}\n\nint\nlame_set_short_threshold_s(lame_global_flags * gfp, float s)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->attackthre_s = s;\n        return 0;\n    }\n    return -1;\n}\n\nfloat\nlame_get_short_threshold_s(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->attackthre_s;\n    }\n    return 0;\n}\n\nint\nlame_set_short_threshold(lame_global_flags * gfp, float lrm, float s)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_set_short_threshold_lrm(gfp, lrm);\n        lame_set_short_threshold_s(gfp, s);\n        return 0;\n    }\n    return -1;\n}\n\n\n/*\n * Input PCM is emphased PCM\n * (for instance from one of the rarely emphased CDs).\n *\n * It is STRONGLY not recommended to use this, because psycho does not\n * take it into account, and last but not least many decoders\n * ignore these bits\n */\nint\nlame_set_emphasis(lame_global_flags * gfp, int emphasis)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* XXX: emphasis should be converted to an enum */\n        if (0 <= emphasis && emphasis < 4) {\n            gfp->emphasis = emphasis;\n            return 0;\n        }\n    }\n    return -1;\n}\n\nint\nlame_get_emphasis(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        assert(0 <= gfp->emphasis && gfp->emphasis < 4);\n        return gfp->emphasis;\n    }\n    return 0;\n}\n\n\n\n\n/***************************************************************/\n/* internal variables, cannot be set...                        */\n/* provided because they may be of use to calling application  */\n/***************************************************************/\n\n/* MPEG version.\n *  0 = MPEG-2\n *  1 = MPEG-1\n * (2 = MPEG-2.5)    \n */\nint\nlame_get_version(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            return gfc->cfg.version;\n        }\n    }\n    return 0;\n}\n\n\n/* Encoder delay. */\nint\nlame_get_encoder_delay(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            return gfc->ov_enc.encoder_delay;\n        }\n    }\n    return 0;\n}\n\n/* padding added to the end of the input */\nint\nlame_get_encoder_padding(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            return gfc->ov_enc.encoder_padding;\n        }\n    }\n    return 0;\n}\n\n\n/* Size of MPEG frame. */\nint\nlame_get_framesize(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            SessionConfig_t const *const cfg = &gfc->cfg;\n            return 576 * cfg->mode_gr;\n        }\n    }\n    return 0;\n}\n\n\n/* Number of frames encoded so far. */\nint\nlame_get_frameNum(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            return gfc->ov_enc.frame_number;\n        }\n    }\n    return 0;\n}\n\nint\nlame_get_mf_samples_to_encode(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            return gfc->sv_enc.mf_samples_to_encode;\n        }\n    }\n    return 0;\n}\n\nint     CDECL\nlame_get_size_mp3buffer(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            int     size;\n            compute_flushbits(gfc, &size);\n            return size;\n        }\n    }\n    return 0;\n}\n\nint\nlame_get_RadioGain(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            return gfc->ov_rpg.RadioGain;\n        }\n    }\n    return 0;\n}\n\nint\nlame_get_AudiophileGain(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            return 0;\n        }\n    }\n    return 0;\n}\n\nfloat\nlame_get_PeakSample(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            return (float) gfc->ov_rpg.PeakSample;\n        }\n    }\n    return 0;\n}\n\nint\nlame_get_noclipGainChange(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            return gfc->ov_rpg.noclipGainChange;\n        }\n    }\n    return 0;\n}\n\nfloat\nlame_get_noclipScale(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            return gfc->ov_rpg.noclipScale;\n        }\n    }\n    return 0;\n}\n\n\n/*\n * LAME's estimate of the total number of frames to be encoded.\n * Only valid if calling program set num_samples.\n */\nint\nlame_get_totalframes(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        lame_internal_flags const *const gfc = gfp->internal_flags;\n        if (is_lame_internal_flags_valid(gfc)) {\n            SessionConfig_t const *const cfg = &gfc->cfg;\n            unsigned long const pcm_samples_per_frame = 576 * cfg->mode_gr;\n            unsigned long pcm_samples_to_encode = gfp->num_samples;\n            unsigned long end_padding = 0;\n\n            /* estimate based on user set num_samples: */\n            if (pcm_samples_to_encode == (0ul-1ul)) {\n                return 0;\n            }\n            if (gfp->samplerate_in != gfp->samplerate_out && gfp->samplerate_in > 0) {\n                double const q = (double)gfp->samplerate_out / gfp->samplerate_in;\n                pcm_samples_to_encode *= q;\n            }\n            pcm_samples_to_encode += 576;\n            end_padding = pcm_samples_per_frame - (pcm_samples_to_encode % pcm_samples_per_frame);\n            if (end_padding < 576) {\n                end_padding += pcm_samples_per_frame;\n            }\n            pcm_samples_to_encode += end_padding;\n            /* check to see if we underestimated totalframes */\n            /*    if (totalframes < gfp->frameNum) */\n            /*        totalframes = gfp->frameNum; */\n            return pcm_samples_to_encode / pcm_samples_per_frame;\n        }\n    }\n    return 0;\n}\n\n\n\n\n\nint\nlame_set_preset(lame_global_flags * gfp, int preset)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->preset = preset;\n        return apply_preset(gfp, preset, 1);\n    }\n    return -1;\n}\n\n\n\nint\nlame_set_asm_optimizations(lame_global_flags * gfp, int optim, int mode)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        mode = (mode == 1 ? 1 : 0);\n        switch (optim) {\n        case MMX:{\n                gfp->asm_optimizations.mmx = mode;\n                return optim;\n            }\n        case AMD_3DNOW:{\n                gfp->asm_optimizations.amd3dnow = mode;\n                return optim;\n            }\n        case SSE:{\n                gfp->asm_optimizations.sse = mode;\n                return optim;\n            }\n        default:\n            return optim;\n        }\n    }\n    return -1;\n}\n\n\nvoid\nlame_set_write_id3tag_automatic(lame_global_flags * gfp, int v)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->write_id3tag_automatic = v;\n    }\n}\n\n\nint\nlame_get_write_id3tag_automatic(lame_global_flags const *gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->write_id3tag_automatic;\n    }\n    return 1;\n}\n\n\n/*\n\nUNDOCUMENTED, experimental settings.  These routines are not prototyped\nin lame.h.  You should not use them, they are experimental and may\nchange.  \n\n*/\n\n\n/*\n *  just another daily changing developer switch  \n */\nvoid CDECL lame_set_tune(lame_global_flags *, float);\n\nvoid\nlame_set_tune(lame_global_flags * gfp, float val)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        gfp->tune_value_a = val;\n        gfp->tune = 1;\n    }\n}\n\n/* Custom msfix hack */\nvoid\nlame_set_msfix(lame_global_flags * gfp, double msfix)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        /* default = 0 */\n        gfp->msfix = msfix;\n    }\n}\n\nfloat\nlame_get_msfix(const lame_global_flags * gfp)\n{\n    if (is_lame_global_flags_valid(gfp)) {\n        return gfp->msfix;\n    }\n    return 0;\n}\n\n#if DEPRECATED_OR_OBSOLETE_CODE_REMOVED\nint CDECL lame_set_preset_expopts(lame_global_flags *, int);\n#else\n#endif\n\nint\nlame_set_preset_expopts(lame_global_flags * gfp, int preset_expopts)\n{\n    (void) gfp;\n    (void) preset_expopts;\n    return 0;\n}\n\n\nint\nlame_set_preset_notune(lame_global_flags * gfp, int preset_notune)\n{\n    (void) gfp;\n    (void) preset_notune;\n    return 0;\n}\n"
  },
  {
    "path": "app/jni/libmp3lame/set_get.h",
    "content": "/*\n * set_get.h -- Internal set/get definitions\n *\n * Copyright (C) 2003 Gabriel Bouvigne / Lame project\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n */\n\n#ifndef __SET_GET_H__\n#define __SET_GET_H__\n\n#include <lame.h>\n\n#if defined(__cplusplus)\nextern  \"C\" {\n#endif\n\n/* select psychoacoustic model */\n\n/* manage short blocks */\n    int CDECL lame_set_short_threshold(lame_global_flags *, float, float);\n    int CDECL lame_set_short_threshold_lrm(lame_global_flags *, float);\n    float CDECL lame_get_short_threshold_lrm(const lame_global_flags *);\n    int CDECL lame_set_short_threshold_s(lame_global_flags *, float);\n    float CDECL lame_get_short_threshold_s(const lame_global_flags *);\n\n\n    int CDECL lame_set_maskingadjust(lame_global_flags *, float);\n    float CDECL lame_get_maskingadjust(const lame_global_flags *);\n\n    int CDECL lame_set_maskingadjust_short(lame_global_flags *, float);\n    float CDECL lame_get_maskingadjust_short(const lame_global_flags *);\n\n/* select ATH formula 4 shape */\n    int CDECL lame_set_ATHcurve(lame_global_flags *, float);\n    float CDECL lame_get_ATHcurve(const lame_global_flags *);\n\n    int CDECL lame_set_preset_notune(lame_global_flags *, int);\n\n/* substep shaping method */\n    int CDECL lame_set_substep(lame_global_flags *, int);\n    int CDECL lame_get_substep(const lame_global_flags *);\n\n/* scalefactors scale */\n    int CDECL lame_set_sfscale(lame_global_flags *, int);\n    int CDECL lame_get_sfscale(const lame_global_flags *);\n\n/* subblock gain */\n    int CDECL lame_set_subblock_gain(lame_global_flags *, int);\n    int CDECL lame_get_subblock_gain(const lame_global_flags *);\n\n\n\n/*presets*/\n    int     apply_preset(lame_global_flags *, int preset, int enforce);\n\n    void CDECL lame_set_tune(lame_t, float); /* FOR INTERNAL USE ONLY */\n    void CDECL lame_set_msfix(lame_t gfp, double msfix);\n\n\n#if defined(__cplusplus)\n}\n#endif\n#endif\n"
  },
  {
    "path": "app/jni/libmp3lame/tables.c",
    "content": "/*\n *\tMPEG layer 3 tables source file\n *\n *\tCopyright (c) 1999 Albert L Faber\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: tables.c,v 1.29 2011/05/07 16:05:17 rbrito Exp $ */\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include \"machine.h\"\n\n#include \"lame.h\"\n#include \"tables.h\"\n\n\nstatic const uint16_t t1HB[] = {\n    1, 1,\n    1, 0\n};\n\nstatic const uint16_t t2HB[] = {\n    1, 2, 1,\n    3, 1, 1,\n    3, 2, 0\n};\n\nstatic const uint16_t t3HB[] = {\n    3, 2, 1,\n    1, 1, 1,\n    3, 2, 0\n};\n\nstatic const uint16_t t5HB[] = {\n    1, 2, 6, 5,\n    3, 1, 4, 4,\n    7, 5, 7, 1,\n    6, 1, 1, 0\n};\n\nstatic const uint16_t t6HB[] = {\n    7, 3, 5, 1,\n    6, 2, 3, 2,\n    5, 4, 4, 1,\n    3, 3, 2, 0\n};\n\nstatic const uint16_t t7HB[] = {\n    1, 2, 10, 19, 16, 10,\n    3, 3, 7, 10, 5, 3,\n    11, 4, 13, 17, 8, 4,\n    12, 11, 18, 15, 11, 2,\n    7, 6, 9, 14, 3, 1,\n    6, 4, 5, 3, 2, 0\n};\n\nstatic const uint16_t t8HB[] = {\n    3, 4, 6, 18, 12, 5,\n    5, 1, 2, 16, 9, 3,\n    7, 3, 5, 14, 7, 3,\n    19, 17, 15, 13, 10, 4,\n    13, 5, 8, 11, 5, 1,\n    12, 4, 4, 1, 1, 0\n};\n\nstatic const uint16_t t9HB[] = {\n    7, 5, 9, 14, 15, 7,\n    6, 4, 5, 5, 6, 7,\n    7, 6, 8, 8, 8, 5,\n    15, 6, 9, 10, 5, 1,\n    11, 7, 9, 6, 4, 1,\n    14, 4, 6, 2, 6, 0\n};\n\nstatic const uint16_t t10HB[] = {\n    1, 2, 10, 23, 35, 30, 12, 17,\n    3, 3, 8, 12, 18, 21, 12, 7,\n    11, 9, 15, 21, 32, 40, 19, 6,\n    14, 13, 22, 34, 46, 23, 18, 7,\n    20, 19, 33, 47, 27, 22, 9, 3,\n    31, 22, 41, 26, 21, 20, 5, 3,\n    14, 13, 10, 11, 16, 6, 5, 1,\n    9, 8, 7, 8, 4, 4, 2, 0\n};\n\nstatic const uint16_t t11HB[] = {\n    3, 4, 10, 24, 34, 33, 21, 15,\n    5, 3, 4, 10, 32, 17, 11, 10,\n    11, 7, 13, 18, 30, 31, 20, 5,\n    25, 11, 19, 59, 27, 18, 12, 5,\n    35, 33, 31, 58, 30, 16, 7, 5,\n    28, 26, 32, 19, 17, 15, 8, 14,\n    14, 12, 9, 13, 14, 9, 4, 1,\n    11, 4, 6, 6, 6, 3, 2, 0\n};\n\nstatic const uint16_t t12HB[] = {\n    9, 6, 16, 33, 41, 39, 38, 26,\n    7, 5, 6, 9, 23, 16, 26, 11,\n    17, 7, 11, 14, 21, 30, 10, 7,\n    17, 10, 15, 12, 18, 28, 14, 5,\n    32, 13, 22, 19, 18, 16, 9, 5,\n    40, 17, 31, 29, 17, 13, 4, 2,\n    27, 12, 11, 15, 10, 7, 4, 1,\n    27, 12, 8, 12, 6, 3, 1, 0\n};\n\nstatic const uint16_t t13HB[] = {\n    1, 5, 14, 21, 34, 51, 46, 71, 42, 52, 68, 52, 67, 44, 43, 19,\n    3, 4, 12, 19, 31, 26, 44, 33, 31, 24, 32, 24, 31, 35, 22, 14,\n    15, 13, 23, 36, 59, 49, 77, 65, 29, 40, 30, 40, 27, 33, 42, 16,\n    22, 20, 37, 61, 56, 79, 73, 64, 43, 76, 56, 37, 26, 31, 25, 14,\n    35, 16, 60, 57, 97, 75, 114, 91, 54, 73, 55, 41, 48, 53, 23, 24,\n    58, 27, 50, 96, 76, 70, 93, 84, 77, 58, 79, 29, 74, 49, 41, 17,\n    47, 45, 78, 74, 115, 94, 90, 79, 69, 83, 71, 50, 59, 38, 36, 15,\n    72, 34, 56, 95, 92, 85, 91, 90, 86, 73, 77, 65, 51, 44, 43, 42,\n    43, 20, 30, 44, 55, 78, 72, 87, 78, 61, 46, 54, 37, 30, 20, 16,\n    53, 25, 41, 37, 44, 59, 54, 81, 66, 76, 57, 54, 37, 18, 39, 11,\n    35, 33, 31, 57, 42, 82, 72, 80, 47, 58, 55, 21, 22, 26, 38, 22,\n    53, 25, 23, 38, 70, 60, 51, 36, 55, 26, 34, 23, 27, 14, 9, 7,\n    34, 32, 28, 39, 49, 75, 30, 52, 48, 40, 52, 28, 18, 17, 9, 5,\n    45, 21, 34, 64, 56, 50, 49, 45, 31, 19, 12, 15, 10, 7, 6, 3,\n    48, 23, 20, 39, 36, 35, 53, 21, 16, 23, 13, 10, 6, 1, 4, 2,\n    16, 15, 17, 27, 25, 20, 29, 11, 17, 12, 16, 8, 1, 1, 0, 1\n};\n\nstatic const uint16_t t15HB[] = {\n    7, 12, 18, 53, 47, 76, 124, 108, 89, 123, 108, 119, 107, 81, 122, 63,\n    13, 5, 16, 27, 46, 36, 61, 51, 42, 70, 52, 83, 65, 41, 59, 36,\n    19, 17, 15, 24, 41, 34, 59, 48, 40, 64, 50, 78, 62, 80, 56, 33,\n    29, 28, 25, 43, 39, 63, 55, 93, 76, 59, 93, 72, 54, 75, 50, 29,\n    52, 22, 42, 40, 67, 57, 95, 79, 72, 57, 89, 69, 49, 66, 46, 27,\n    77, 37, 35, 66, 58, 52, 91, 74, 62, 48, 79, 63, 90, 62, 40, 38,\n    125, 32, 60, 56, 50, 92, 78, 65, 55, 87, 71, 51, 73, 51, 70, 30,\n    109, 53, 49, 94, 88, 75, 66, 122, 91, 73, 56, 42, 64, 44, 21, 25,\n    90, 43, 41, 77, 73, 63, 56, 92, 77, 66, 47, 67, 48, 53, 36, 20,\n    71, 34, 67, 60, 58, 49, 88, 76, 67, 106, 71, 54, 38, 39, 23, 15,\n    109, 53, 51, 47, 90, 82, 58, 57, 48, 72, 57, 41, 23, 27, 62, 9,\n    86, 42, 40, 37, 70, 64, 52, 43, 70, 55, 42, 25, 29, 18, 11, 11,\n    118, 68, 30, 55, 50, 46, 74, 65, 49, 39, 24, 16, 22, 13, 14, 7,\n    91, 44, 39, 38, 34, 63, 52, 45, 31, 52, 28, 19, 14, 8, 9, 3,\n    123, 60, 58, 53, 47, 43, 32, 22, 37, 24, 17, 12, 15, 10, 2, 1,\n    71, 37, 34, 30, 28, 20, 17, 26, 21, 16, 10, 6, 8, 6, 2, 0\n};\n\nstatic const uint16_t t16HB[] = {\n    1, 5, 14, 44, 74, 63, 110, 93, 172, 149, 138, 242, 225, 195, 376, 17,\n    3, 4, 12, 20, 35, 62, 53, 47, 83, 75, 68, 119, 201, 107, 207, 9,\n    15, 13, 23, 38, 67, 58, 103, 90, 161, 72, 127, 117, 110, 209, 206, 16,\n    45, 21, 39, 69, 64, 114, 99, 87, 158, 140, 252, 212, 199, 387, 365, 26,\n    75, 36, 68, 65, 115, 101, 179, 164, 155, 264, 246, 226, 395, 382, 362, 9,\n    66, 30, 59, 56, 102, 185, 173, 265, 142, 253, 232, 400, 388, 378, 445, 16,\n    111, 54, 52, 100, 184, 178, 160, 133, 257, 244, 228, 217, 385, 366, 715, 10,\n    98, 48, 91, 88, 165, 157, 148, 261, 248, 407, 397, 372, 380, 889, 884, 8,\n    85, 84, 81, 159, 156, 143, 260, 249, 427, 401, 392, 383, 727, 713, 708, 7,\n    154, 76, 73, 141, 131, 256, 245, 426, 406, 394, 384, 735, 359, 710, 352, 11,\n    139, 129, 67, 125, 247, 233, 229, 219, 393, 743, 737, 720, 885, 882, 439, 4,\n    243, 120, 118, 115, 227, 223, 396, 746, 742, 736, 721, 712, 706, 223, 436, 6,\n    202, 224, 222, 218, 216, 389, 386, 381, 364, 888, 443, 707, 440, 437, 1728, 4,\n    747, 211, 210, 208, 370, 379, 734, 723, 714, 1735, 883, 877, 876, 3459, 865, 2,\n    377, 369, 102, 187, 726, 722, 358, 711, 709, 866, 1734, 871, 3458, 870, 434, 0,\n    12, 10, 7, 11, 10, 17, 11, 9, 13, 12, 10, 7, 5, 3, 1, 3\n};\n\nstatic const uint16_t t24HB[] = {\n    15, 13, 46, 80, 146, 262, 248, 434, 426, 669, 653, 649, 621, 517, 1032, 88,\n    14, 12, 21, 38, 71, 130, 122, 216, 209, 198, 327, 345, 319, 297, 279, 42,\n    47, 22, 41, 74, 68, 128, 120, 221, 207, 194, 182, 340, 315, 295, 541, 18,\n    81, 39, 75, 70, 134, 125, 116, 220, 204, 190, 178, 325, 311, 293, 271, 16,\n    147, 72, 69, 135, 127, 118, 112, 210, 200, 188, 352, 323, 306, 285, 540, 14,\n    263, 66, 129, 126, 119, 114, 214, 202, 192, 180, 341, 317, 301, 281, 262, 12,\n    249, 123, 121, 117, 113, 215, 206, 195, 185, 347, 330, 308, 291, 272, 520, 10,\n    435, 115, 111, 109, 211, 203, 196, 187, 353, 332, 313, 298, 283, 531, 381, 17,\n    427, 212, 208, 205, 201, 193, 186, 177, 169, 320, 303, 286, 268, 514, 377, 16,\n    335, 199, 197, 191, 189, 181, 174, 333, 321, 305, 289, 275, 521, 379, 371, 11,\n    668, 184, 183, 179, 175, 344, 331, 314, 304, 290, 277, 530, 383, 373, 366, 10,\n    652, 346, 171, 168, 164, 318, 309, 299, 287, 276, 263, 513, 375, 368, 362, 6,\n    648, 322, 316, 312, 307, 302, 292, 284, 269, 261, 512, 376, 370, 364, 359, 4,\n    620, 300, 296, 294, 288, 282, 273, 266, 515, 380, 374, 369, 365, 361, 357, 2,\n    1033, 280, 278, 274, 267, 264, 259, 382, 378, 372, 367, 363, 360, 358, 356, 0,\n    43, 20, 19, 17, 15, 13, 11, 9, 7, 6, 4, 7, 5, 3, 1, 3\n};\n\nstatic const uint16_t t32HB[] = {\n    1 << 0, 5 << 1, 4 << 1, 5 << 2, 6 << 1, 5 << 2, 4 << 2, 4 << 3,\n    7 << 1, 3 << 2, 6 << 2, 0 << 3, 7 << 2, 2 << 3, 3 << 3, 1 << 4\n};\n\nstatic const uint16_t t33HB[] = {\n    15 << 0, 14 << 1, 13 << 1, 12 << 2, 11 << 1, 10 << 2, 9 << 2, 8 << 3,\n    7 << 1, 6 << 2, 5 << 2, 4 << 3, 3 << 2, 2 << 3, 1 << 3, 0 << 4\n};\n\n\nconst uint8_t t1l[] = {\n    1, 4,\n    3, 5\n};\n\nstatic const uint8_t t2l[] = {\n    1, 4, 7,\n    4, 5, 7,\n    6, 7, 8\n};\n\nstatic const uint8_t t3l[] = {\n    2, 3, 7,\n    4, 4, 7,\n    6, 7, 8\n};\n\nstatic const uint8_t t5l[] = {\n    1, 4, 7, 8,\n    4, 5, 8, 9,\n    7, 8, 9, 10,\n    8, 8, 9, 10\n};\n\nstatic const uint8_t t6l[] = {\n    3, 4, 6, 8,\n    4, 4, 6, 7,\n    5, 6, 7, 8,\n    7, 7, 8, 9\n};\n\nstatic const uint8_t t7l[] = {\n    1, 4, 7, 9, 9, 10,\n    4, 6, 8, 9, 9, 10,\n    7, 7, 9, 10, 10, 11,\n    8, 9, 10, 11, 11, 11,\n    8, 9, 10, 11, 11, 12,\n    9, 10, 11, 12, 12, 12\n};\n\nstatic const uint8_t t8l[] = {\n    2, 4, 7, 9, 9, 10,\n    4, 4, 6, 10, 10, 10,\n    7, 6, 8, 10, 10, 11,\n    9, 10, 10, 11, 11, 12,\n    9, 9, 10, 11, 12, 12,\n    10, 10, 11, 11, 13, 13\n};\n\nstatic const uint8_t t9l[] = {\n    3, 4, 6, 7, 9, 10,\n    4, 5, 6, 7, 8, 10,\n    5, 6, 7, 8, 9, 10,\n    7, 7, 8, 9, 9, 10,\n    8, 8, 9, 9, 10, 11,\n    9, 9, 10, 10, 11, 11\n};\n\nstatic const uint8_t t10l[] = {\n    1, 4, 7, 9, 10, 10, 10, 11,\n    4, 6, 8, 9, 10, 11, 10, 10,\n    7, 8, 9, 10, 11, 12, 11, 11,\n    8, 9, 10, 11, 12, 12, 11, 12,\n    9, 10, 11, 12, 12, 12, 12, 12,\n    10, 11, 12, 12, 13, 13, 12, 13,\n    9, 10, 11, 12, 12, 12, 13, 13,\n    10, 10, 11, 12, 12, 13, 13, 13\n};\n\nstatic const uint8_t t11l[] = {\n    2, 4, 6, 8, 9, 10, 9, 10,\n    4, 5, 6, 8, 10, 10, 9, 10,\n    6, 7, 8, 9, 10, 11, 10, 10,\n    8, 8, 9, 11, 10, 12, 10, 11,\n    9, 10, 10, 11, 11, 12, 11, 12,\n    9, 10, 11, 12, 12, 13, 12, 13,\n    9, 9, 9, 10, 11, 12, 12, 12,\n    9, 9, 10, 11, 12, 12, 12, 12\n};\n\nstatic const uint8_t t12l[] = {\n    4, 4, 6, 8, 9, 10, 10, 10,\n    4, 5, 6, 7, 9, 9, 10, 10,\n    6, 6, 7, 8, 9, 10, 9, 10,\n    7, 7, 8, 8, 9, 10, 10, 10,\n    8, 8, 9, 9, 10, 10, 10, 11,\n    9, 9, 10, 10, 10, 11, 10, 11,\n    9, 9, 9, 10, 10, 11, 11, 12,\n    10, 10, 10, 11, 11, 11, 11, 12\n};\n\nstatic const uint8_t t13l[] = {\n    1, 5, 7, 8, 9, 10, 10, 11, 10, 11, 12, 12, 13, 13, 14, 14,\n    4, 6, 8, 9, 10, 10, 11, 11, 11, 11, 12, 12, 13, 14, 14, 14,\n    7, 8, 9, 10, 11, 11, 12, 12, 11, 12, 12, 13, 13, 14, 15, 15,\n    8, 9, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 15, 15,\n    9, 9, 11, 11, 12, 12, 13, 13, 12, 13, 13, 14, 14, 15, 15, 16,\n    10, 10, 11, 12, 12, 12, 13, 13, 13, 13, 14, 13, 15, 15, 16, 16,\n    10, 11, 12, 12, 13, 13, 13, 13, 13, 14, 14, 14, 15, 15, 16, 16,\n    11, 11, 12, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 16, 18, 18,\n    10, 10, 11, 12, 12, 13, 13, 14, 14, 14, 14, 15, 15, 16, 17, 17,\n    11, 11, 12, 12, 13, 13, 13, 15, 14, 15, 15, 16, 16, 16, 18, 17,\n    11, 12, 12, 13, 13, 14, 14, 15, 14, 15, 16, 15, 16, 17, 18, 19,\n    12, 12, 12, 13, 14, 14, 14, 14, 15, 15, 15, 16, 17, 17, 17, 18,\n    12, 13, 13, 14, 14, 15, 14, 15, 16, 16, 17, 17, 17, 18, 18, 18,\n    13, 13, 14, 15, 15, 15, 16, 16, 16, 16, 16, 17, 18, 17, 18, 18,\n    14, 14, 14, 15, 15, 15, 17, 16, 16, 19, 17, 17, 17, 19, 18, 18,\n    13, 14, 15, 16, 16, 16, 17, 16, 17, 17, 18, 18, 21, 20, 21, 18\n};\n\nstatic const uint8_t t15l[] = {\n    3, 5, 6, 8, 8, 9, 10, 10, 10, 11, 11, 12, 12, 12, 13, 14,\n    5, 5, 7, 8, 9, 9, 10, 10, 10, 11, 11, 12, 12, 12, 13, 13,\n    6, 7, 7, 8, 9, 9, 10, 10, 10, 11, 11, 12, 12, 13, 13, 13,\n    7, 8, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 13,\n    8, 8, 9, 9, 10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 13, 13,\n    9, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 13, 13, 13, 14,\n    10, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 13, 14, 14,\n    10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 14,\n    10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 14, 14, 14,\n    10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14,\n    11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 13, 14, 15, 14,\n    11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15,\n    12, 12, 11, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14, 15, 15,\n    12, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 14, 15, 15,\n    13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 14, 15,\n    13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 15, 15, 15, 15\n};\n\nstatic const uint8_t t16_5l[] = {\n    1, 5, 7, 9, 10, 10, 11, 11, 12, 12, 12, 13, 13, 13, 14, 11,\n    4, 6, 8, 9, 10, 11, 11, 11, 12, 12, 12, 13, 14, 13, 14, 11,\n    7, 8, 9, 10, 11, 11, 12, 12, 13, 12, 13, 13, 13, 14, 14, 12,\n    9, 9, 10, 11, 11, 12, 12, 12, 13, 13, 14, 14, 14, 15, 15, 13,\n    10, 10, 11, 11, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 12,\n    10, 10, 11, 11, 12, 13, 13, 14, 13, 14, 14, 15, 15, 15, 16, 13,\n    11, 11, 11, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 16, 13,\n    11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 15, 15, 17, 17, 13,\n    11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 13,\n    12, 12, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 15, 16, 15, 14,\n    12, 13, 12, 13, 14, 14, 14, 14, 15, 16, 16, 16, 17, 17, 16, 13,\n    13, 13, 13, 13, 14, 14, 15, 16, 16, 16, 16, 16, 16, 15, 16, 14,\n    13, 14, 14, 14, 14, 15, 15, 15, 15, 17, 16, 16, 16, 16, 18, 14,\n    15, 14, 14, 14, 15, 15, 16, 16, 16, 18, 17, 17, 17, 19, 17, 14,\n    14, 15, 13, 14, 16, 16, 15, 16, 16, 17, 18, 17, 19, 17, 16, 14,\n    11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 12\n};\n\nstatic const uint8_t t16l[] = {\n    1, 5, 7, 9, 10, 10, 11, 11, 12, 12, 12, 13, 13, 13, 14, 10,\n    4, 6, 8, 9, 10, 11, 11, 11, 12, 12, 12, 13, 14, 13, 14, 10,\n    7, 8, 9, 10, 11, 11, 12, 12, 13, 12, 13, 13, 13, 14, 14, 11,\n    9, 9, 10, 11, 11, 12, 12, 12, 13, 13, 14, 14, 14, 15, 15, 12,\n    10, 10, 11, 11, 12, 12, 13, 13, 13, 14, 14, 14, 15, 15, 15, 11,\n    10, 10, 11, 11, 12, 13, 13, 14, 13, 14, 14, 15, 15, 15, 16, 12,\n    11, 11, 11, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 16, 12,\n    11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 15, 15, 17, 17, 12,\n    11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 12,\n    12, 12, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 15, 16, 15, 13,\n    12, 13, 12, 13, 14, 14, 14, 14, 15, 16, 16, 16, 17, 17, 16, 12,\n    13, 13, 13, 13, 14, 14, 15, 16, 16, 16, 16, 16, 16, 15, 16, 13,\n    13, 14, 14, 14, 14, 15, 15, 15, 15, 17, 16, 16, 16, 16, 18, 13,\n    15, 14, 14, 14, 15, 15, 16, 16, 16, 18, 17, 17, 17, 19, 17, 13,\n    14, 15, 13, 14, 16, 16, 15, 16, 16, 17, 18, 17, 19, 17, 16, 13,\n    10, 10, 10, 11, 11, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 10\n};\n\nstatic const uint8_t t24l[] = {\n    4, 5, 7, 8, 9, 10, 10, 11, 11, 12, 12, 12, 12, 12, 13, 10,\n    5, 6, 7, 8, 9, 10, 10, 11, 11, 11, 12, 12, 12, 12, 12, 10,\n    7, 7, 8, 9, 9, 10, 10, 11, 11, 11, 11, 12, 12, 12, 13, 9,\n    8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 9,\n    9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, 12, 12, 12, 13, 9,\n    10, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 9,\n    10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 9,\n    11, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 10,\n    11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 10,\n    11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 13, 10,\n    12, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 10,\n    12, 12, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 10,\n    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 10,\n    12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 10,\n    13, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 10,\n    9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 6\n};\n\nconst uint8_t t32l[] = {\n    1 + 0, 4 + 1, 4 + 1, 5 + 2, 4 + 1, 6 + 2, 5 + 2, 6 + 3,\n    4 + 1, 5 + 2, 5 + 2, 6 + 3, 5 + 2, 6 + 3, 6 + 3, 6 + 4\n};\n\nconst uint8_t t33l[] = {\n    4 + 0, 4 + 1, 4 + 1, 4 + 2, 4 + 1, 4 + 2, 4 + 2, 4 + 3,\n    4 + 1, 4 + 2, 4 + 2, 4 + 3, 4 + 2, 4 + 3, 4 + 3, 4 + 4\n};\n\n\nconst struct huffcodetab ht[HTN] = {\n    /* xlen, linmax, table, hlen */\n    {0, 0, NULL, NULL},\n    {2, 0, t1HB, t1l},\n    {3, 0, t2HB, t2l},\n    {3, 0, t3HB, t3l},\n    {0, 0, NULL, NULL}, /* Apparently not used */\n    {4, 0, t5HB, t5l},\n    {4, 0, t6HB, t6l},\n    {6, 0, t7HB, t7l},\n    {6, 0, t8HB, t8l},\n    {6, 0, t9HB, t9l},\n    {8, 0, t10HB, t10l},\n    {8, 0, t11HB, t11l},\n    {8, 0, t12HB, t12l},\n    {16, 0, t13HB, t13l},\n    {0, 0, NULL, t16_5l}, /* Apparently not used */\n    {16, 0, t15HB, t15l},\n\n    {1, 1, t16HB, t16l},\n    {2, 3, t16HB, t16l},\n    {3, 7, t16HB, t16l},\n    {4, 15, t16HB, t16l},\n    {6, 63, t16HB, t16l},\n    {8, 255, t16HB, t16l},\n    {10, 1023, t16HB, t16l},\n    {13, 8191, t16HB, t16l},\n\n    {4, 15, t24HB, t24l},\n    {5, 31, t24HB, t24l},\n    {6, 63, t24HB, t24l},\n    {7, 127, t24HB, t24l},\n    {8, 255, t24HB, t24l},\n    {9, 511, t24HB, t24l},\n    {11, 2047, t24HB, t24l},\n    {13, 8191, t24HB, t24l},\n\n    {0, 0, t32HB, t32l},\n    {0, 0, t33HB, t33l},\n};\n\n\n\n\n\n/*  for (i = 0; i < 16*16; i++) {\n *      largetbl[i] = ((ht[16].hlen[i]) << 16) + ht[24].hlen[i];\n *  }\n */\nconst uint32_t largetbl[16 * 16] = {\n    0x010004, 0x050005, 0x070007, 0x090008, 0x0a0009, 0x0a000a, 0x0b000a, 0x0b000b,\n    0x0c000b, 0x0c000c, 0x0c000c, 0x0d000c, 0x0d000c, 0x0d000c, 0x0e000d, 0x0a000a,\n    0x040005, 0x060006, 0x080007, 0x090008, 0x0a0009, 0x0b000a, 0x0b000a, 0x0b000b,\n    0x0c000b, 0x0c000b, 0x0c000c, 0x0d000c, 0x0e000c, 0x0d000c, 0x0e000c, 0x0a000a,\n    0x070007, 0x080007, 0x090008, 0x0a0009, 0x0b0009, 0x0b000a, 0x0c000a, 0x0c000b,\n    0x0d000b, 0x0c000b, 0x0d000b, 0x0d000c, 0x0d000c, 0x0e000c, 0x0e000d, 0x0b0009,\n    0x090008, 0x090008, 0x0a0009, 0x0b0009, 0x0b000a, 0x0c000a, 0x0c000a, 0x0c000b,\n    0x0d000b, 0x0d000b, 0x0e000b, 0x0e000c, 0x0e000c, 0x0f000c, 0x0f000c, 0x0c0009,\n    0x0a0009, 0x0a0009, 0x0b0009, 0x0b000a, 0x0c000a, 0x0c000a, 0x0d000a, 0x0d000b,\n    0x0d000b, 0x0e000b, 0x0e000c, 0x0e000c, 0x0f000c, 0x0f000c, 0x0f000d, 0x0b0009,\n    0x0a000a, 0x0a0009, 0x0b000a, 0x0b000a, 0x0c000a, 0x0d000a, 0x0d000b, 0x0e000b,\n    0x0d000b, 0x0e000b, 0x0e000c, 0x0f000c, 0x0f000c, 0x0f000c, 0x10000c, 0x0c0009,\n    0x0b000a, 0x0b000a, 0x0b000a, 0x0c000a, 0x0d000a, 0x0d000b, 0x0d000b, 0x0d000b,\n    0x0e000b, 0x0e000c, 0x0e000c, 0x0e000c, 0x0f000c, 0x0f000c, 0x10000d, 0x0c0009,\n    0x0b000b, 0x0b000a, 0x0c000a, 0x0c000a, 0x0d000b, 0x0d000b, 0x0d000b, 0x0e000b,\n    0x0e000c, 0x0f000c, 0x0f000c, 0x0f000c, 0x0f000c, 0x11000d, 0x11000d, 0x0c000a,\n    0x0b000b, 0x0c000b, 0x0c000b, 0x0d000b, 0x0d000b, 0x0d000b, 0x0e000b, 0x0e000b,\n    0x0f000b, 0x0f000c, 0x0f000c, 0x0f000c, 0x10000c, 0x10000d, 0x10000d, 0x0c000a,\n    0x0c000b, 0x0c000b, 0x0c000b, 0x0d000b, 0x0d000b, 0x0e000b, 0x0e000b, 0x0f000c,\n    0x0f000c, 0x0f000c, 0x0f000c, 0x10000c, 0x0f000d, 0x10000d, 0x0f000d, 0x0d000a,\n    0x0c000c, 0x0d000b, 0x0c000b, 0x0d000b, 0x0e000b, 0x0e000c, 0x0e000c, 0x0e000c,\n    0x0f000c, 0x10000c, 0x10000c, 0x10000d, 0x11000d, 0x11000d, 0x10000d, 0x0c000a,\n    0x0d000c, 0x0d000c, 0x0d000b, 0x0d000b, 0x0e000b, 0x0e000c, 0x0f000c, 0x10000c,\n    0x10000c, 0x10000c, 0x10000c, 0x10000d, 0x10000d, 0x0f000d, 0x10000d, 0x0d000a,\n    0x0d000c, 0x0e000c, 0x0e000c, 0x0e000c, 0x0e000c, 0x0f000c, 0x0f000c, 0x0f000c,\n    0x0f000c, 0x11000c, 0x10000d, 0x10000d, 0x10000d, 0x10000d, 0x12000d, 0x0d000a,\n    0x0f000c, 0x0e000c, 0x0e000c, 0x0e000c, 0x0f000c, 0x0f000c, 0x10000c, 0x10000c,\n    0x10000d, 0x12000d, 0x11000d, 0x11000d, 0x11000d, 0x13000d, 0x11000d, 0x0d000a,\n    0x0e000d, 0x0f000c, 0x0d000c, 0x0e000c, 0x10000c, 0x10000c, 0x0f000c, 0x10000d,\n    0x10000d, 0x11000d, 0x12000d, 0x11000d, 0x13000d, 0x11000d, 0x10000d, 0x0d000a,\n    0x0a0009, 0x0a0009, 0x0a0009, 0x0b0009, 0x0b0009, 0x0c0009, 0x0c0009, 0x0c0009,\n    0x0d0009, 0x0d0009, 0x0d0009, 0x0d000a, 0x0d000a, 0x0d000a, 0x0d000a, 0x0a0006\n};\n\n/*  for (i = 0; i < 3*3; i++) {\n *      table23[i] = ((ht[2].hlen[i]) << 16) + ht[3].hlen[i];\n *  }\n */\nconst uint32_t table23[3 * 3] = {\n    0x010002, 0x040003, 0x070007,\n    0x040004, 0x050004, 0x070007,\n    0x060006, 0x070007, 0x080008\n};\n\n/*   for (i = 0; i < 4*4; i++) {\n *       table56[i] = ((ht[5].hlen[i]) << 16) + ht[6].hlen[i];\n *   }\n */\nconst uint32_t table56[4 * 4] = {\n    0x010003, 0x040004, 0x070006, 0x080008, 0x040004, 0x050004, 0x080006, 0x090007,\n    0x070005, 0x080006, 0x090007, 0x0a0008, 0x080007, 0x080007, 0x090008, 0x0a0009\n};\n\n\n\n/* \n * 0: MPEG-2 LSF\n * 1: MPEG-1\n * 2: MPEG-2.5 LSF FhG extention                  (1995-07-11 shn)\n */\n\ntypedef enum {\n    MPEG_2 = 0,\n    MPEG_1 = 1,\n    MPEG_25 = 2\n} MPEG_t;\n\nconst int bitrate_table[3][16] = {\n    {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, -1}, /* MPEG 2 */\n    {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1}, /* MPEG 1 */\n    {0, 8, 16, 24, 32, 40, 48, 56, 64, -1, -1, -1, -1, -1, -1, -1}, /* MPEG 2.5 */\n};\n\nconst int samplerate_table[3][4] = {\n    {22050, 24000, 16000, -1}, /* MPEG 2 */\n    {44100, 48000, 32000, -1}, /* MPEG 1 */\n    {11025, 12000, 8000, -1}, /* MPEG 2.5 */\n};\n\nint\nlame_get_bitrate(int mpeg_version, int table_index)\n{\n    if (0 <= mpeg_version && mpeg_version <= 2) {\n        if (0 <= table_index && table_index <= 15) {\n            return bitrate_table[mpeg_version][table_index];\n        }\n    }\n    return -1;\n}\n\nint\nlame_get_samplerate(int mpeg_version, int table_index)\n{\n    if (0 <= mpeg_version && mpeg_version <= 2) {\n        if (0 <= table_index && table_index <= 3) {\n            return samplerate_table[mpeg_version][table_index];\n        }\n    }\n    return -1;\n}\n\n\n/* This is the scfsi_band table from 2.4.2.7 of the IS */\nconst int scfsi_band[5] = { 0, 6, 11, 16, 21 };\n\n/* end of tables.c */\n"
  },
  {
    "path": "app/jni/libmp3lame/tables.h",
    "content": "/*\n *\tMPEG layer 3 tables include file\n *\n *\tCopyright (c) 1999 Albert L Faber\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_TABLES_H\n#define LAME_TABLES_H\n\n#if 0\ntypedef struct {\n    unsigned char no;\n    unsigned char width;\n    unsigned char minval_2;\n    float   quiet_thr;\n    float   norm;\n    float   bark;\n} type1_t;\n\ntypedef struct {\n    unsigned char no;\n    unsigned char width;\n    float   quiet_thr;\n    float   norm;\n    float   SNR;\n    float   bark;\n} type2_t;\n\ntypedef struct {\n    unsigned int no:5;\n    unsigned int cbw:3;\n    unsigned int bu:6;\n    unsigned int bo:6;\n    unsigned int w1_576:10;\n    unsigned int w2_576:10;\n} type34_t;\n\ntypedef struct {\n    size_t  len1;\n    const type1_t *const tab1;\n    size_t  len2;\n    const type2_t *const tab2;\n    size_t  len3;\n    const type34_t *const tab3;\n    size_t  len4;\n    const type34_t *const tab4;\n} type5_t;\n\nextern const type5_t table5[6];\n\n#endif\n\n#define HTN\t34\n\nstruct huffcodetab {\n    const unsigned int xlen;          /* max. x-index+   */\n    const unsigned int linmax;        /* max number to be stored in linbits */\n    const uint16_t *table;      /* pointer to array[xlen][ylen]  */\n    const uint8_t *hlen;        /* pointer to array[xlen][ylen]  */\n};\n\nextern const struct huffcodetab ht[HTN];\n    /* global memory block   */\n    /* array of all huffcodtable headers */\n    /* 0..31 Huffman code table 0..31  */\n    /* 32,33 count1-tables   */\n\nextern const uint8_t t32l[];\nextern const uint8_t t33l[];\n\nextern const uint32_t largetbl[16 * 16];\nextern const uint32_t table23[3 * 3];\nextern const uint32_t table56[4 * 4];\n\nextern const int scfsi_band[5];\n\nextern const int bitrate_table    [3][16];\nextern const int samplerate_table [3][ 4];\n\n#endif /* LAME_TABLES_H */\n"
  },
  {
    "path": "app/jni/libmp3lame/takehiro.c",
    "content": "/*\n *\tMP3 huffman table selecting and bit counting\n *\n *\tCopyright (c) 1999-2005 Takehiro TOMINAGA\n *\tCopyright (c) 2002-2005 Gabriel Bouvigne\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: takehiro.c,v 1.79 2011/05/07 16:05:17 rbrito Exp $ */\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n\n#include <string.h>\n#include <strings.h>\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"quantize_pvt.h\"\n#include \"tables.h\"\n\n\nstatic const struct {\n    const int region0_count;\n    const int region1_count;\n} subdv_table[23] = {\n    {\n    0, 0},              /* 0 bands */\n    {\n    0, 0},              /* 1 bands */\n    {\n    0, 0},              /* 2 bands */\n    {\n    0, 0},              /* 3 bands */\n    {\n    0, 0},              /* 4 bands */\n    {\n    0, 1},              /* 5 bands */\n    {\n    1, 1},              /* 6 bands */\n    {\n    1, 1},              /* 7 bands */\n    {\n    1, 2},              /* 8 bands */\n    {\n    2, 2},              /* 9 bands */\n    {\n    2, 3},              /* 10 bands */\n    {\n    2, 3},              /* 11 bands */\n    {\n    3, 4},              /* 12 bands */\n    {\n    3, 4},              /* 13 bands */\n    {\n    3, 4},              /* 14 bands */\n    {\n    4, 5},              /* 15 bands */\n    {\n    4, 5},              /* 16 bands */\n    {\n    4, 6},              /* 17 bands */\n    {\n    5, 6},              /* 18 bands */\n    {\n    5, 6},              /* 19 bands */\n    {\n    5, 7},              /* 20 bands */\n    {\n    6, 7},              /* 21 bands */\n    {\n    6, 7},              /* 22 bands */\n};\n\n\n\n\n\n/*********************************************************************\n * nonlinear quantization of xr \n * More accurate formula than the ISO formula.  Takes into account\n * the fact that we are quantizing xr -> ix, but we want ix^4/3 to be \n * as close as possible to x^4/3.  (taking the nearest int would mean\n * ix is as close as possible to xr, which is different.)\n *\n * From Segher Boessenkool <segher@eastsite.nl>  11/1999\n *\n * 09/2000: ASM code removed in favor of IEEE754 hack by Takehiro\n * Tominaga. If you need the ASM code, check CVS circa Aug 2000.\n *\n * 01/2004: Optimizations by Gabriel Bouvigne\n *********************************************************************/\n\n\n\n\n\nstatic void\nquantize_lines_xrpow_01(unsigned int l, FLOAT istep, const FLOAT * xr, int *ix)\n{\n    const FLOAT compareval0 = (1.0f - 0.4054f) / istep;\n    unsigned int i;\n\n    assert(l > 0);\n    assert(l % 2 == 0);\n    for (i = 0; i < l; i += 2) {\n        FLOAT const xr_0 = xr[i+0];\n        FLOAT const xr_1 = xr[i+1];\n        int const ix_0 = (compareval0 > xr_0) ? 0 : 1;\n        int const ix_1 = (compareval0 > xr_1) ? 0 : 1;\n        ix[i+0] = ix_0;\n        ix[i+1] = ix_1;\n    }\n}\n\n\n\n#ifdef TAKEHIRO_IEEE754_HACK\n\ntypedef union {\n    float   f;\n    int     i;\n} fi_union;\n\n#define MAGIC_FLOAT (65536*(128))\n#define MAGIC_INT 0x4b000000\n\n\nstatic void\nquantize_lines_xrpow(unsigned int l, FLOAT istep, const FLOAT * xp, int *pi)\n{\n    fi_union *fi;\n    unsigned int remaining;\n\n    assert(l > 0);\n\n    fi = (fi_union *) pi;\n\n    l = l >> 1;\n    remaining = l % 2;\n    l = l >> 1;\n    while (l--) {\n        double  x0 = istep * xp[0];\n        double  x1 = istep * xp[1];\n        double  x2 = istep * xp[2];\n        double  x3 = istep * xp[3];\n\n        x0 += MAGIC_FLOAT;\n        fi[0].f = x0;\n        x1 += MAGIC_FLOAT;\n        fi[1].f = x1;\n        x2 += MAGIC_FLOAT;\n        fi[2].f = x2;\n        x3 += MAGIC_FLOAT;\n        fi[3].f = x3;\n\n        fi[0].f = x0 + adj43asm[fi[0].i - MAGIC_INT];\n        fi[1].f = x1 + adj43asm[fi[1].i - MAGIC_INT];\n        fi[2].f = x2 + adj43asm[fi[2].i - MAGIC_INT];\n        fi[3].f = x3 + adj43asm[fi[3].i - MAGIC_INT];\n\n        fi[0].i -= MAGIC_INT;\n        fi[1].i -= MAGIC_INT;\n        fi[2].i -= MAGIC_INT;\n        fi[3].i -= MAGIC_INT;\n        fi += 4;\n        xp += 4;\n    };\n    if (remaining) {\n        double  x0 = istep * xp[0];\n        double  x1 = istep * xp[1];\n\n        x0 += MAGIC_FLOAT;\n        fi[0].f = x0;\n        x1 += MAGIC_FLOAT;\n        fi[1].f = x1;\n\n        fi[0].f = x0 + adj43asm[fi[0].i - MAGIC_INT];\n        fi[1].f = x1 + adj43asm[fi[1].i - MAGIC_INT];\n\n        fi[0].i -= MAGIC_INT;\n        fi[1].i -= MAGIC_INT;\n    }\n\n}\n\n\n#else\n\n/*********************************************************************\n * XRPOW_FTOI is a macro to convert floats to ints.  \n * if XRPOW_FTOI(x) = nearest_int(x), then QUANTFAC(x)=adj43asm[x]\n *                                         ROUNDFAC= -0.0946\n *\n * if XRPOW_FTOI(x) = floor(x), then QUANTFAC(x)=asj43[x]   \n *                                   ROUNDFAC=0.4054\n *\n * Note: using floor() or (int) is extremely slow. On machines where\n * the TAKEHIRO_IEEE754_HACK code above does not work, it is worthwile\n * to write some ASM for XRPOW_FTOI().  \n *********************************************************************/\n#define XRPOW_FTOI(src,dest) ((dest) = (int)(src))\n#define QUANTFAC(rx)  adj43[rx]\n#define ROUNDFAC 0.4054\n\n\nstatic void\nquantize_lines_xrpow(unsigned int l, FLOAT istep, const FLOAT * xr, int *ix)\n{\n    unsigned int remaining;\n\n    assert(l > 0);\n\n    l = l >> 1;\n    remaining = l % 2;\n    l = l >> 1;\n    while (l--) {\n        FLOAT   x0, x1, x2, x3;\n        int     rx0, rx1, rx2, rx3;\n\n        x0 = *xr++ * istep;\n        x1 = *xr++ * istep;\n        XRPOW_FTOI(x0, rx0);\n        x2 = *xr++ * istep;\n        XRPOW_FTOI(x1, rx1);\n        x3 = *xr++ * istep;\n        XRPOW_FTOI(x2, rx2);\n        x0 += QUANTFAC(rx0);\n        XRPOW_FTOI(x3, rx3);\n        x1 += QUANTFAC(rx1);\n        XRPOW_FTOI(x0, *ix++);\n        x2 += QUANTFAC(rx2);\n        XRPOW_FTOI(x1, *ix++);\n        x3 += QUANTFAC(rx3);\n        XRPOW_FTOI(x2, *ix++);\n        XRPOW_FTOI(x3, *ix++);\n    };\n    if (remaining) {\n        FLOAT   x0, x1;\n        int     rx0, rx1;\n\n        x0 = *xr++ * istep;\n        x1 = *xr++ * istep;\n        XRPOW_FTOI(x0, rx0);\n        XRPOW_FTOI(x1, rx1);\n        x0 += QUANTFAC(rx0);\n        x1 += QUANTFAC(rx1);\n        XRPOW_FTOI(x0, *ix++);\n        XRPOW_FTOI(x1, *ix++);\n    }\n\n}\n\n\n\n#endif\n\n\n\n/*********************************************************************\n * Quantization function\n * This function will select which lines to quantize and call the\n * proper quantization function\n *********************************************************************/\n\nstatic void\nquantize_xrpow(const FLOAT * xp, int *pi, FLOAT istep, gr_info const *const cod_info,\n               calc_noise_data const *prev_noise)\n{\n    /* quantize on xr^(3/4) instead of xr */\n    int     sfb;\n    int     sfbmax;\n    int     j = 0;\n    int     prev_data_use;\n    int    *iData;\n    int     accumulate = 0;\n    int     accumulate01 = 0;\n    int    *acc_iData;\n    const FLOAT *acc_xp;\n\n    iData = pi;\n    acc_xp = xp;\n    acc_iData = iData;\n\n\n    /* Reusing previously computed data does not seems to work if global gain\n       is changed. Finding why it behaves this way would allow to use a cache of \n       previously computed values (let's 10 cached values per sfb) that would \n       probably provide a noticeable speedup */\n    prev_data_use = (prev_noise && (cod_info->global_gain == prev_noise->global_gain));\n\n    if (cod_info->block_type == SHORT_TYPE)\n        sfbmax = 38;\n    else\n        sfbmax = 21;\n\n    for (sfb = 0; sfb <= sfbmax; sfb++) {\n        int     step = -1;\n\n        if (prev_data_use || cod_info->block_type == NORM_TYPE) {\n            step =\n                cod_info->global_gain\n                - ((cod_info->scalefac[sfb] + (cod_info->preflag ? pretab[sfb] : 0))\n                   << (cod_info->scalefac_scale + 1))\n                - cod_info->subblock_gain[cod_info->window[sfb]] * 8;\n        }\n        assert(cod_info->width[sfb] >= 0);\n        if (prev_data_use && (prev_noise->step[sfb] == step)) {\n            /* do not recompute this part,\n               but compute accumulated lines */\n            if (accumulate) {\n                quantize_lines_xrpow(accumulate, istep, acc_xp, acc_iData);\n                accumulate = 0;\n            }\n            if (accumulate01) {\n                quantize_lines_xrpow_01(accumulate01, istep, acc_xp, acc_iData);\n                accumulate01 = 0;\n            }\n        }\n        else {          /*should compute this part */\n            int     l;\n            l = cod_info->width[sfb];\n\n            if ((j + cod_info->width[sfb]) > cod_info->max_nonzero_coeff) {\n                /*do not compute upper zero part */\n                int     usefullsize;\n                usefullsize = cod_info->max_nonzero_coeff - j + 1;\n                memset(&pi[cod_info->max_nonzero_coeff], 0,\n                       sizeof(int) * (576 - cod_info->max_nonzero_coeff));\n                l = usefullsize;\n\n                if (l < 0) {\n                    l = 0;\n                }\n\n                /* no need to compute higher sfb values */\n                sfb = sfbmax + 1;\n            }\n\n            /*accumulate lines to quantize */\n            if (!accumulate && !accumulate01) {\n                acc_iData = iData;\n                acc_xp = xp;\n            }\n            if (prev_noise &&\n                prev_noise->sfb_count1 > 0 &&\n                sfb >= prev_noise->sfb_count1 &&\n                prev_noise->step[sfb] > 0 && step >= prev_noise->step[sfb]) {\n\n                if (accumulate) {\n                    quantize_lines_xrpow(accumulate, istep, acc_xp, acc_iData);\n                    accumulate = 0;\n                    acc_iData = iData;\n                    acc_xp = xp;\n                }\n                accumulate01 += l;\n            }\n            else {\n                if (accumulate01) {\n                    quantize_lines_xrpow_01(accumulate01, istep, acc_xp, acc_iData);\n                    accumulate01 = 0;\n                    acc_iData = iData;\n                    acc_xp = xp;\n                }\n                accumulate += l;\n            }\n\n            if (l <= 0) {\n                /*  rh: 20040215\n                 *  may happen due to \"prev_data_use\" optimization \n                 */\n                if (accumulate01) {\n                    quantize_lines_xrpow_01(accumulate01, istep, acc_xp, acc_iData);\n                    accumulate01 = 0;\n                }\n                if (accumulate) {\n                    quantize_lines_xrpow(accumulate, istep, acc_xp, acc_iData);\n                    accumulate = 0;\n                }\n\n                break;  /* ends for-loop */\n            }\n        }\n        if (sfb <= sfbmax) {\n            iData += cod_info->width[sfb];\n            xp += cod_info->width[sfb];\n            j += cod_info->width[sfb];\n        }\n    }\n    if (accumulate) {   /*last data part */\n        quantize_lines_xrpow(accumulate, istep, acc_xp, acc_iData);\n        accumulate = 0;\n    }\n    if (accumulate01) { /*last data part */\n        quantize_lines_xrpow_01(accumulate01, istep, acc_xp, acc_iData);\n        accumulate01 = 0;\n    }\n\n}\n\n\n\n\n/*************************************************************************/\n/*\t      ix_max\t\t\t\t\t\t\t */\n/*************************************************************************/\n\nstatic int\nix_max(const int *ix, const int *end)\n{\n    int     max1 = 0, max2 = 0;\n\n    do {\n        int const x1 = *ix++;\n        int const x2 = *ix++;\n        if (max1 < x1)\n            max1 = x1;\n\n        if (max2 < x2)\n            max2 = x2;\n    } while (ix < end);\n    if (max1 < max2)\n        max1 = max2;\n    return max1;\n}\n\n\n\n\n\n\n\n\nstatic int\ncount_bit_ESC(const int *ix, const int *const end, int t1, const int t2, unsigned int *const s)\n{\n    /* ESC-table is used */\n    unsigned int const linbits = ht[t1].xlen * 65536u + ht[t2].xlen;\n    unsigned int sum = 0, sum2;\n\n    do {\n        unsigned int x = *ix++;\n        unsigned int y = *ix++;\n\n        if (x >= 15u) {\n            x = 15u;\n            sum += linbits;\n        }\n        if (y >= 15u) {\n            y = 15u;\n            sum += linbits;\n        }\n        x <<= 4u;\n        x += y;\n        sum += largetbl[x];\n    } while (ix < end);\n\n    sum2 = sum & 0xffffu;\n    sum >>= 16u;\n\n    if (sum > sum2) {\n        sum = sum2;\n        t1 = t2;\n    }\n\n    *s += sum;\n    return t1;\n}\n\n\nstatic int\ncount_bit_noESC(const int *ix, const int *end, int mx, unsigned int *s)\n{\n    /* No ESC-words */\n    unsigned int sum1 = 0;\n    const uint8_t *const hlen1 = ht[1].hlen;\n    (void) mx;\n\n    do {\n        unsigned int const x0 = *ix++;\n        unsigned int const x1 = *ix++;\n        sum1 += hlen1[ x0+x0 + x1 ];\n    } while (ix < end);\n\n    *s += sum1;\n    return 1;\n}\n\n\nstatic const int huf_tbl_noESC[] = {\n    1, 2, 5, 7, 7, 10, 10, 13, 13, 13, 13, 13, 13, 13, 13\n};\n\n\nstatic int\ncount_bit_noESC_from2(const int *ix, const int *end, int max, unsigned int *s)\n{\n    int t1 = huf_tbl_noESC[max - 1];\n    /* No ESC-words */\n    const unsigned int xlen = ht[t1].xlen;\n    uint32_t const* table = (t1 == 2) ? &table23[0] : &table56[0];\n    unsigned int sum = 0, sum2;\n\n    do {\n        unsigned int const x0 = *ix++;\n        unsigned int const x1 = *ix++;\n        sum += table[ x0 * xlen + x1 ];\n    } while (ix < end);\n\n    sum2 = sum & 0xffffu;\n    sum >>= 16u;\n\n    if (sum > sum2) {\n        sum = sum2;\n        t1++;\n    }\n\n    *s += sum;\n    return t1;\n}\n\n\ninline static int\ncount_bit_noESC_from3(const int *ix, const int *end, int max, unsigned int * s)\n{\n    int t1 = huf_tbl_noESC[max - 1];\n    /* No ESC-words */\n    unsigned int sum1 = 0;\n    unsigned int sum2 = 0;\n    unsigned int sum3 = 0;\n    const unsigned int xlen = ht[t1].xlen;\n    const uint8_t *const hlen1 = ht[t1].hlen;\n    const uint8_t *const hlen2 = ht[t1 + 1].hlen;\n    const uint8_t *const hlen3 = ht[t1 + 2].hlen;\n    int     t;\n\n    do {\n        unsigned int x0 = *ix++;\n        unsigned int x1 = *ix++;\n        unsigned int x = x0 * xlen + x1;\n        sum1 += hlen1[x];\n        sum2 += hlen2[x];\n        sum3 += hlen3[x];\n    } while (ix < end);\n\n    t = t1;\n    if (sum1 > sum2) {\n        sum1 = sum2;\n        t++;\n    }\n    if (sum1 > sum3) {\n        sum1 = sum3;\n        t = t1 + 2;\n    }\n    *s += sum1;\n\n    return t;  \n}\n\n\n/*************************************************************************/\n/*\t      choose table\t\t\t\t\t\t */\n/*************************************************************************/\n\n/*\n  Choose the Huffman table that will encode ix[begin..end] with\n  the fewest bits.\n\n  Note: This code contains knowledge about the sizes and characteristics\n  of the Huffman tables as defined in the IS (Table B.7), and will not work\n  with any arbitrary tables.\n*/\nstatic int count_bit_null(const int* ix, const int* end, int max, unsigned int* s)\n{\n    (void) ix;\n    (void) end;\n    (void) max;\n    (void) s;\n    return 0;\n}\n\ntypedef int (*count_fnc)(const int* ix, const int* end, int max, unsigned int* s);\n  \nstatic count_fnc count_fncs[] = \n{ &count_bit_null\n, &count_bit_noESC\n, &count_bit_noESC_from2\n, &count_bit_noESC_from2\n, &count_bit_noESC_from3\n, &count_bit_noESC_from3\n, &count_bit_noESC_from3\n, &count_bit_noESC_from3\n, &count_bit_noESC_from3\n, &count_bit_noESC_from3\n, &count_bit_noESC_from3\n, &count_bit_noESC_from3\n, &count_bit_noESC_from3\n, &count_bit_noESC_from3\n, &count_bit_noESC_from3\n, &count_bit_noESC_from3\n};\n\nstatic int\nchoose_table_nonMMX(const int *ix, const int *const end, int *const _s)\n{\n    unsigned int* s = (unsigned int*)_s;\n    unsigned int  max;\n    int     choice, choice2;\n    max = ix_max(ix, end);\n\n    if (max <= 15) {\n      return count_fncs[max](ix, end, max, s);\n    }\n    /* try tables with linbits */\n    if (max > IXMAX_VAL) {\n        *s = LARGE_BITS;\n        return -1;\n    }\n    max -= 15u;\n    for (choice2 = 24; choice2 < 32; choice2++) {\n        if (ht[choice2].linmax >= max) {\n            break;\n        }\n    }\n\n    for (choice = choice2 - 8; choice < 24; choice++) {\n        if (ht[choice].linmax >= max) {\n            break;\n        }\n    }\n    return count_bit_ESC(ix, end, choice, choice2, s);\n}\n\n\n\n/*************************************************************************/\n/*\t      count_bit\t\t\t\t\t\t\t */\n/*************************************************************************/\nint\nnoquant_count_bits(lame_internal_flags const *const gfc,\n                   gr_info * const gi, calc_noise_data * prev_noise)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     bits = 0;\n    int     i, a1, a2;\n    int const *const ix = gi->l3_enc;\n\n    i = Min(576, ((gi->max_nonzero_coeff + 2) >> 1) << 1);\n\n    if (prev_noise)\n        prev_noise->sfb_count1 = 0;\n\n    /* Determine count1 region */\n    for (; i > 1; i -= 2)\n        if (ix[i - 1] | ix[i - 2])\n            break;\n    gi->count1 = i;\n\n    /* Determines the number of bits to encode the quadruples. */\n    a1 = a2 = 0;\n    for (; i > 3; i -= 4) {\n        int x4 = ix[i-4];\n        int x3 = ix[i-3];\n        int x2 = ix[i-2];\n        int x1 = ix[i-1];\n        int     p;\n        /* hack to check if all values <= 1 */\n        if ((unsigned int) (x4 | x3 | x2 | x1) > 1)\n            break;\n\n        p = ((x4 * 2 + x3) * 2 + x2) * 2 + x1;\n        a1 += t32l[p];\n        a2 += t33l[p];\n    }\n\n    bits = a1;\n    gi->count1table_select = 0;\n    if (a1 > a2) {\n        bits = a2;\n        gi->count1table_select = 1;\n    }\n\n    gi->count1bits = bits;\n    gi->big_values = i;\n    if (i == 0)\n        return bits;\n\n    if (gi->block_type == SHORT_TYPE) {\n        a1 = 3 * gfc->scalefac_band.s[3];\n        if (a1 > gi->big_values)\n            a1 = gi->big_values;\n        a2 = gi->big_values;\n\n    }\n    else if (gi->block_type == NORM_TYPE) {\n        assert(i <= 576); /* bv_scf has 576 entries (0..575) */\n        a1 = gi->region0_count = gfc->sv_qnt.bv_scf[i - 2];\n        a2 = gi->region1_count = gfc->sv_qnt.bv_scf[i - 1];\n\n        assert(a1 + a2 + 2 < SBPSY_l);\n        a2 = gfc->scalefac_band.l[a1 + a2 + 2];\n        a1 = gfc->scalefac_band.l[a1 + 1];\n        if (a2 < i)\n            gi->table_select[2] = gfc->choose_table(ix + a2, ix + i, &bits);\n\n    }\n    else {\n        gi->region0_count = 7;\n        /*gi->region1_count = SBPSY_l - 7 - 1; */\n        gi->region1_count = SBMAX_l - 1 - 7 - 1;\n        a1 = gfc->scalefac_band.l[7 + 1];\n        a2 = i;\n        if (a1 > a2) {\n            a1 = a2;\n        }\n    }\n\n\n    /* have to allow for the case when bigvalues < region0 < region1 */\n    /* (and region0, region1 are ignored) */\n    a1 = Min(a1, i);\n    a2 = Min(a2, i);\n\n    assert(a1 >= 0);\n    assert(a2 >= 0);\n\n    /* Count the number of bits necessary to code the bigvalues region. */\n    if (0 < a1)\n        gi->table_select[0] = gfc->choose_table(ix, ix + a1, &bits);\n    if (a1 < a2)\n        gi->table_select[1] = gfc->choose_table(ix + a1, ix + a2, &bits);\n    if (cfg->use_best_huffman == 2) {\n        gi->part2_3_length = bits;\n        best_huffman_divide(gfc, gi);\n        bits = gi->part2_3_length;\n    }\n\n\n    if (prev_noise) {\n        if (gi->block_type == NORM_TYPE) {\n            int     sfb = 0;\n            while (gfc->scalefac_band.l[sfb] < gi->big_values) {\n                sfb++;\n            }\n            prev_noise->sfb_count1 = sfb;\n        }\n    }\n\n    return bits;\n}\n\nint\ncount_bits(lame_internal_flags const *const gfc,\n           const FLOAT * const xr, gr_info * const gi, calc_noise_data * prev_noise)\n{\n    int    *const ix = gi->l3_enc;\n\n    /* since quantize_xrpow uses table lookup, we need to check this first: */\n    FLOAT const w = (IXMAX_VAL) / IPOW20(gi->global_gain);\n\n    if (gi->xrpow_max > w)\n        return LARGE_BITS;\n\n    quantize_xrpow(xr, ix, IPOW20(gi->global_gain), gi, prev_noise);\n\n    if (gfc->sv_qnt.substep_shaping & 2) {\n        int     sfb, j = 0;\n        /* 0.634521682242439 = 0.5946*2**(.5*0.1875) */\n        int const gain = gi->global_gain + gi->scalefac_scale;\n        const FLOAT roundfac = 0.634521682242439 / IPOW20(gain);\n        for (sfb = 0; sfb < gi->sfbmax; sfb++) {\n            int const width = gi->width[sfb];\n            assert(width >= 0);\n            if (!gfc->sv_qnt.pseudohalf[sfb]) {\n                j += width;\n            }\n            else {\n                int     k;\n                for (k = j, j += width; k < j; ++k) {\n                    ix[k] = (xr[k] >= roundfac) ? ix[k] : 0;\n                }\n            }\n        }\n    }\n    return noquant_count_bits(gfc, gi, prev_noise);\n}\n\n/***********************************************************************\n  re-calculate the best scalefac_compress using scfsi\n  the saved bits are kept in the bit reservoir.\n **********************************************************************/\n\n\ninline static void\nrecalc_divide_init(const lame_internal_flags * const gfc,\n                   gr_info const *cod_info,\n                   int const *const ix, int r01_bits[], int r01_div[], int r0_tbl[], int r1_tbl[])\n{\n    int     r0, r1, bigv, r0t, r1t, bits;\n\n    bigv = cod_info->big_values;\n\n    for (r0 = 0; r0 <= 7 + 15; r0++) {\n        r01_bits[r0] = LARGE_BITS;\n    }\n\n    for (r0 = 0; r0 < 16; r0++) {\n        int const a1 = gfc->scalefac_band.l[r0 + 1];\n        int     r0bits;\n        if (a1 >= bigv)\n            break;\n        r0bits = 0;\n        r0t = gfc->choose_table(ix, ix + a1, &r0bits);\n\n        for (r1 = 0; r1 < 8; r1++) {\n            int const a2 = gfc->scalefac_band.l[r0 + r1 + 2];\n            if (a2 >= bigv)\n                break;\n\n            bits = r0bits;\n            r1t = gfc->choose_table(ix + a1, ix + a2, &bits);\n            if (r01_bits[r0 + r1] > bits) {\n                r01_bits[r0 + r1] = bits;\n                r01_div[r0 + r1] = r0;\n                r0_tbl[r0 + r1] = r0t;\n                r1_tbl[r0 + r1] = r1t;\n            }\n        }\n    }\n}\n\ninline static void\nrecalc_divide_sub(const lame_internal_flags * const gfc,\n                  const gr_info * cod_info2,\n                  gr_info * const gi,\n                  const int *const ix,\n                  const int r01_bits[], const int r01_div[], const int r0_tbl[], const int r1_tbl[])\n{\n    int     bits, r2, a2, bigv, r2t;\n\n    bigv = cod_info2->big_values;\n\n    for (r2 = 2; r2 < SBMAX_l + 1; r2++) {\n        a2 = gfc->scalefac_band.l[r2];\n        if (a2 >= bigv)\n            break;\n\n        bits = r01_bits[r2 - 2] + cod_info2->count1bits;\n        if (gi->part2_3_length <= bits)\n            break;\n\n        r2t = gfc->choose_table(ix + a2, ix + bigv, &bits);\n        if (gi->part2_3_length <= bits)\n            continue;\n\n        memcpy(gi, cod_info2, sizeof(gr_info));\n        gi->part2_3_length = bits;\n        gi->region0_count = r01_div[r2 - 2];\n        gi->region1_count = r2 - 2 - r01_div[r2 - 2];\n        gi->table_select[0] = r0_tbl[r2 - 2];\n        gi->table_select[1] = r1_tbl[r2 - 2];\n        gi->table_select[2] = r2t;\n    }\n}\n\n\n\n\nvoid\nbest_huffman_divide(const lame_internal_flags * const gfc, gr_info * const gi)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     i, a1, a2;\n    gr_info cod_info2;\n    int const *const ix = gi->l3_enc;\n\n    int     r01_bits[7 + 15 + 1];\n    int     r01_div[7 + 15 + 1];\n    int     r0_tbl[7 + 15 + 1];\n    int     r1_tbl[7 + 15 + 1];\n\n\n    /* SHORT BLOCK stuff fails for MPEG2 */\n    if (gi->block_type == SHORT_TYPE && cfg->mode_gr == 1)\n        return;\n\n\n    memcpy(&cod_info2, gi, sizeof(gr_info));\n    if (gi->block_type == NORM_TYPE) {\n        recalc_divide_init(gfc, gi, ix, r01_bits, r01_div, r0_tbl, r1_tbl);\n        recalc_divide_sub(gfc, &cod_info2, gi, ix, r01_bits, r01_div, r0_tbl, r1_tbl);\n    }\n\n    i = cod_info2.big_values;\n    if (i == 0 || (unsigned int) (ix[i - 2] | ix[i - 1]) > 1)\n        return;\n\n    i = gi->count1 + 2;\n    if (i > 576)\n        return;\n\n    /* Determines the number of bits to encode the quadruples. */\n    memcpy(&cod_info2, gi, sizeof(gr_info));\n    cod_info2.count1 = i;\n    a1 = a2 = 0;\n\n    assert(i <= 576);\n\n    for (; i > cod_info2.big_values; i -= 4) {\n        int const p = ((ix[i - 4] * 2 + ix[i - 3]) * 2 + ix[i - 2]) * 2 + ix[i - 1];\n        a1 += t32l[p];\n        a2 += t33l[p];\n    }\n    cod_info2.big_values = i;\n\n    cod_info2.count1table_select = 0;\n    if (a1 > a2) {\n        a1 = a2;\n        cod_info2.count1table_select = 1;\n    }\n\n    cod_info2.count1bits = a1;\n\n    if (cod_info2.block_type == NORM_TYPE)\n        recalc_divide_sub(gfc, &cod_info2, gi, ix, r01_bits, r01_div, r0_tbl, r1_tbl);\n    else {\n        /* Count the number of bits necessary to code the bigvalues region. */\n        cod_info2.part2_3_length = a1;\n        a1 = gfc->scalefac_band.l[7 + 1];\n        if (a1 > i) {\n            a1 = i;\n        }\n        if (a1 > 0)\n            cod_info2.table_select[0] =\n                gfc->choose_table(ix, ix + a1, (int *) &cod_info2.part2_3_length);\n        if (i > a1)\n            cod_info2.table_select[1] =\n                gfc->choose_table(ix + a1, ix + i, (int *) &cod_info2.part2_3_length);\n        if (gi->part2_3_length > cod_info2.part2_3_length)\n            memcpy(gi, &cod_info2, sizeof(gr_info));\n    }\n}\n\nstatic const int slen1_n[16] = { 1, 1, 1, 1, 8, 2, 2, 2, 4, 4, 4, 8, 8, 8, 16, 16 };\nstatic const int slen2_n[16] = { 1, 2, 4, 8, 1, 2, 4, 8, 2, 4, 8, 2, 4, 8, 4, 8 };\nconst int slen1_tab[16] = { 0, 0, 0, 0, 3, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4 };\nconst int slen2_tab[16] = { 0, 1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 3 };\n\nstatic void\nscfsi_calc(int ch, III_side_info_t * l3_side)\n{\n    unsigned int i;\n    int     s1, s2, c1, c2;\n    int     sfb;\n    gr_info *const gi = &l3_side->tt[1][ch];\n    gr_info const *const g0 = &l3_side->tt[0][ch];\n\n    for (i = 0; i < (sizeof(scfsi_band) / sizeof(int)) - 1; i++) {\n        for (sfb = scfsi_band[i]; sfb < scfsi_band[i + 1]; sfb++) {\n            if (g0->scalefac[sfb] != gi->scalefac[sfb]\n                && gi->scalefac[sfb] >= 0)\n                break;\n        }\n        if (sfb == scfsi_band[i + 1]) {\n            for (sfb = scfsi_band[i]; sfb < scfsi_band[i + 1]; sfb++) {\n                gi->scalefac[sfb] = -1;\n            }\n            l3_side->scfsi[ch][i] = 1;\n        }\n    }\n\n    s1 = c1 = 0;\n    for (sfb = 0; sfb < 11; sfb++) {\n        if (gi->scalefac[sfb] == -1)\n            continue;\n        c1++;\n        if (s1 < gi->scalefac[sfb])\n            s1 = gi->scalefac[sfb];\n    }\n\n    s2 = c2 = 0;\n    for (; sfb < SBPSY_l; sfb++) {\n        if (gi->scalefac[sfb] == -1)\n            continue;\n        c2++;\n        if (s2 < gi->scalefac[sfb])\n            s2 = gi->scalefac[sfb];\n    }\n\n    for (i = 0; i < 16; i++) {\n        if (s1 < slen1_n[i] && s2 < slen2_n[i]) {\n            int const c = slen1_tab[i] * c1 + slen2_tab[i] * c2;\n            if (gi->part2_length > c) {\n                gi->part2_length = c;\n                gi->scalefac_compress = (int)i;\n            }\n        }\n    }\n}\n\n/*\nFind the optimal way to store the scalefactors.\nOnly call this routine after final scalefactors have been\nchosen and the channel/granule will not be re-encoded.\n */\nvoid\nbest_scalefac_store(const lame_internal_flags * gfc,\n                    const int gr, const int ch, III_side_info_t * const l3_side)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    /* use scalefac_scale if we can */\n    gr_info *const gi = &l3_side->tt[gr][ch];\n    int     sfb, i, j, l;\n    int     recalc = 0;\n\n    /* remove scalefacs from bands with ix=0.  This idea comes\n     * from the AAC ISO docs.  added mt 3/00 */\n    /* check if l3_enc=0 */\n    j = 0;\n    for (sfb = 0; sfb < gi->sfbmax; sfb++) {\n        int const width = gi->width[sfb];\n        assert(width >= 0);\n        for (l = j, j += width; l < j; ++l) {\n            if (gi->l3_enc[l] != 0)\n                break;\n        }\n        if (l == j)\n            gi->scalefac[sfb] = recalc = -2; /* anything goes. */\n        /*  only best_scalefac_store and calc_scfsi \n         *  know--and only they should know--about the magic number -2. \n         */\n    }\n\n    if (!gi->scalefac_scale && !gi->preflag) {\n        int     s = 0;\n        for (sfb = 0; sfb < gi->sfbmax; sfb++)\n            if (gi->scalefac[sfb] > 0)\n                s |= gi->scalefac[sfb];\n\n        if (!(s & 1) && s != 0) {\n            for (sfb = 0; sfb < gi->sfbmax; sfb++)\n                if (gi->scalefac[sfb] > 0)\n                    gi->scalefac[sfb] >>= 1;\n\n            gi->scalefac_scale = recalc = 1;\n        }\n    }\n\n    if (!gi->preflag && gi->block_type != SHORT_TYPE && cfg->mode_gr == 2) {\n        for (sfb = 11; sfb < SBPSY_l; sfb++)\n            if (gi->scalefac[sfb] < pretab[sfb] && gi->scalefac[sfb] != -2)\n                break;\n        if (sfb == SBPSY_l) {\n            for (sfb = 11; sfb < SBPSY_l; sfb++)\n                if (gi->scalefac[sfb] > 0)\n                    gi->scalefac[sfb] -= pretab[sfb];\n\n            gi->preflag = recalc = 1;\n        }\n    }\n\n    for (i = 0; i < 4; i++)\n        l3_side->scfsi[ch][i] = 0;\n\n    if (cfg->mode_gr == 2 && gr == 1\n        && l3_side->tt[0][ch].block_type != SHORT_TYPE\n        && l3_side->tt[1][ch].block_type != SHORT_TYPE) {\n        scfsi_calc(ch, l3_side);\n        recalc = 0;\n    }\n    for (sfb = 0; sfb < gi->sfbmax; sfb++) {\n        if (gi->scalefac[sfb] == -2) {\n            gi->scalefac[sfb] = 0; /* if anything goes, then 0 is a good choice */\n        }\n    }\n    if (recalc) {\n        (void) scale_bitcount(gfc, gi);\n    }\n}\n\n\n#ifndef NDEBUG\nstatic int\nall_scalefactors_not_negative(int const *scalefac, int n)\n{\n    int     i;\n    for (i = 0; i < n; ++i) {\n        if (scalefac[i] < 0)\n            return 0;\n    }\n    return 1;\n}\n#endif\n\n\n/* number of bits used to encode scalefacs */\n\n/* 18*slen1_tab[i] + 18*slen2_tab[i] */\nstatic const int scale_short[16] = {\n    0, 18, 36, 54, 54, 36, 54, 72, 54, 72, 90, 72, 90, 108, 108, 126\n};\n\n/* 17*slen1_tab[i] + 18*slen2_tab[i] */\nstatic const int scale_mixed[16] = {\n    0, 18, 36, 54, 51, 35, 53, 71, 52, 70, 88, 69, 87, 105, 104, 122\n};\n\n/* 11*slen1_tab[i] + 10*slen2_tab[i] */\nstatic const int scale_long[16] = {\n    0, 10, 20, 30, 33, 21, 31, 41, 32, 42, 52, 43, 53, 63, 64, 74\n};\n\n\n/*************************************************************************/\n/*            scale_bitcount                                             */\n/*************************************************************************/\n\n/* Also calculates the number of bits necessary to code the scalefactors. */\n\nstatic int\nmpeg1_scale_bitcount(const lame_internal_flags * gfc, gr_info * const cod_info)\n{\n    int     k, sfb, max_slen1 = 0, max_slen2 = 0;\n\n    /* maximum values */\n    const int *tab;\n    int    *const scalefac = cod_info->scalefac;\n\n    (void) gfc;\n    assert(all_scalefactors_not_negative(scalefac, cod_info->sfbmax));\n\n    if (cod_info->block_type == SHORT_TYPE) {\n        tab = scale_short;\n        if (cod_info->mixed_block_flag)\n            tab = scale_mixed;\n    }\n    else {              /* block_type == 1,2,or 3 */\n        tab = scale_long;\n        if (!cod_info->preflag) {\n            for (sfb = 11; sfb < SBPSY_l; sfb++)\n                if (scalefac[sfb] < pretab[sfb])\n                    break;\n\n            if (sfb == SBPSY_l) {\n                cod_info->preflag = 1;\n                for (sfb = 11; sfb < SBPSY_l; sfb++)\n                    scalefac[sfb] -= pretab[sfb];\n            }\n        }\n    }\n\n    for (sfb = 0; sfb < cod_info->sfbdivide; sfb++)\n        if (max_slen1 < scalefac[sfb])\n            max_slen1 = scalefac[sfb];\n\n    for (; sfb < cod_info->sfbmax; sfb++)\n        if (max_slen2 < scalefac[sfb])\n            max_slen2 = scalefac[sfb];\n\n    /* from Takehiro TOMINAGA <tominaga@isoternet.org> 10/99\n     * loop over *all* posible values of scalefac_compress to find the\n     * one which uses the smallest number of bits.  ISO would stop\n     * at first valid index */\n    cod_info->part2_length = LARGE_BITS;\n    for (k = 0; k < 16; k++) {\n        if (max_slen1 < slen1_n[k] && max_slen2 < slen2_n[k]\n            && cod_info->part2_length > tab[k]) {\n            cod_info->part2_length = tab[k];\n            cod_info->scalefac_compress = k;\n        }\n    }\n    return cod_info->part2_length == LARGE_BITS;\n}\n\n\n\n/*\n  table of largest scalefactor values for MPEG2\n*/\nstatic const int max_range_sfac_tab[6][4] = {\n    {15, 15, 7, 7},\n    {15, 15, 7, 0},\n    {7, 3, 0, 0},\n    {15, 31, 31, 0},\n    {7, 7, 7, 0},\n    {3, 3, 0, 0}\n};\n\n\n\n\n/*************************************************************************/\n/*            scale_bitcount_lsf                                         */\n/*************************************************************************/\n\n/* Also counts the number of bits to encode the scalefacs but for MPEG 2 */\n/* Lower sampling frequencies  (24, 22.05 and 16 kHz.)                   */\n\n/*  This is reverse-engineered from section 2.4.3.2 of the MPEG2 IS,     */\n/* \"Audio Decoding Layer III\"                                            */\n\nstatic int\nmpeg2_scale_bitcount(const lame_internal_flags * gfc, gr_info * const cod_info)\n{\n    int     table_number, row_in_table, partition, nr_sfb, window, over;\n    int     i, sfb, max_sfac[4];\n    const int *partition_table;\n    int const *const scalefac = cod_info->scalefac;\n\n    /*\n       Set partition table. Note that should try to use table one,\n       but do not yet...\n     */\n    if (cod_info->preflag)\n        table_number = 2;\n    else\n        table_number = 0;\n\n    for (i = 0; i < 4; i++)\n        max_sfac[i] = 0;\n\n    if (cod_info->block_type == SHORT_TYPE) {\n        row_in_table = 1;\n        partition_table = &nr_of_sfb_block[table_number][row_in_table][0];\n        for (sfb = 0, partition = 0; partition < 4; partition++) {\n            nr_sfb = partition_table[partition] / 3;\n            for (i = 0; i < nr_sfb; i++, sfb++)\n                for (window = 0; window < 3; window++)\n                    if (scalefac[sfb * 3 + window] > max_sfac[partition])\n                        max_sfac[partition] = scalefac[sfb * 3 + window];\n        }\n    }\n    else {\n        row_in_table = 0;\n        partition_table = &nr_of_sfb_block[table_number][row_in_table][0];\n        for (sfb = 0, partition = 0; partition < 4; partition++) {\n            nr_sfb = partition_table[partition];\n            for (i = 0; i < nr_sfb; i++, sfb++)\n                if (scalefac[sfb] > max_sfac[partition])\n                    max_sfac[partition] = scalefac[sfb];\n        }\n    }\n\n    for (over = 0, partition = 0; partition < 4; partition++) {\n        if (max_sfac[partition] > max_range_sfac_tab[table_number][partition])\n            over++;\n    }\n    if (!over) {\n        /*\n           Since no bands have been over-amplified, we can set scalefac_compress\n           and slen[] for the formatter\n         */\n        static const int log2tab[] = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4 };\n\n        int     slen1, slen2, slen3, slen4;\n\n        cod_info->sfb_partition_table = nr_of_sfb_block[table_number][row_in_table];\n        for (partition = 0; partition < 4; partition++)\n            cod_info->slen[partition] = log2tab[max_sfac[partition]];\n\n        /* set scalefac_compress */\n        slen1 = cod_info->slen[0];\n        slen2 = cod_info->slen[1];\n        slen3 = cod_info->slen[2];\n        slen4 = cod_info->slen[3];\n\n        switch (table_number) {\n        case 0:\n            cod_info->scalefac_compress = (((slen1 * 5) + slen2) << 4)\n                + (slen3 << 2)\n                + slen4;\n            break;\n\n        case 1:\n            cod_info->scalefac_compress = 400 + (((slen1 * 5) + slen2) << 2)\n                + slen3;\n            break;\n\n        case 2:\n            cod_info->scalefac_compress = 500 + (slen1 * 3) + slen2;\n            break;\n\n        default:\n            ERRORF(gfc, \"intensity stereo not implemented yet\\n\");\n            break;\n        }\n    }\n#ifdef DEBUG\n    if (over)\n        ERRORF(gfc, \"---WARNING !! Amplification of some bands over limits\\n\");\n#endif\n    if (!over) {\n        assert(cod_info->sfb_partition_table);\n        cod_info->part2_length = 0;\n        for (partition = 0; partition < 4; partition++)\n            cod_info->part2_length +=\n                cod_info->slen[partition] * cod_info->sfb_partition_table[partition];\n    }\n    return over;\n}\n\n\nint\nscale_bitcount(const lame_internal_flags * gfc, gr_info * cod_info)\n{\n    if (gfc->cfg.mode_gr == 2) {\n        return mpeg1_scale_bitcount(gfc, cod_info);\n    }\n    else {\n        return mpeg2_scale_bitcount(gfc, cod_info);\n    }\n}\n\n\n#ifdef MMX_choose_table\nextern int choose_table_MMX(const int *ix, const int *const end, int *const s);\n#endif\n\nvoid\nhuffman_init(lame_internal_flags * const gfc)\n{\n    int     i;\n\n    gfc->choose_table = choose_table_nonMMX;\n\n#ifdef MMX_choose_table\n    if (gfc->CPU_features.MMX) {\n        gfc->choose_table = choose_table_MMX;\n    }\n#endif\n\n    for (i = 2; i <= 576; i += 2) {\n        int     scfb_anz = 0, bv_index;\n        while (gfc->scalefac_band.l[++scfb_anz] < i);\n\n        bv_index = subdv_table[scfb_anz].region0_count;\n        while (gfc->scalefac_band.l[bv_index + 1] > i)\n            bv_index--;\n\n        if (bv_index < 0) {\n            /* this is an indication that everything is going to\n               be encoded as region0:  bigvalues < region0 < region1\n               so lets set region0, region1 to some value larger\n               than bigvalues */\n            bv_index = subdv_table[scfb_anz].region0_count;\n        }\n\n        gfc->sv_qnt.bv_scf[i - 2] = bv_index;\n\n        bv_index = subdv_table[scfb_anz].region1_count;\n        while (gfc->scalefac_band.l[bv_index + gfc->sv_qnt.bv_scf[i - 2] + 2] > i)\n            bv_index--;\n\n        if (bv_index < 0) {\n            bv_index = subdv_table[scfb_anz].region1_count;\n        }\n\n        gfc->sv_qnt.bv_scf[i - 1] = bv_index;\n    }\n}\n"
  },
  {
    "path": "app/jni/libmp3lame/util.c",
    "content": "/*\n *\tlame utility library source file\n *\n *\tCopyright (c) 1999 Albert L Faber\n *\tCopyright (c) 2000-2005 Alexander Leidinger\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: util.c,v 1.154.2.1 2012/01/08 23:49:58 robert Exp $ */\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include <malloc.h>\n#include <strings.h>\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"tables.h\"\n\n#define PRECOMPUTE\n#if defined(__FreeBSD__) && !defined(__alpha__)\n# include <machine/floatingpoint.h>\n#endif\n\n\n/***********************************************************************\n*\n*  Global Function Definitions\n*\n***********************************************************************/\n/*empty and close mallocs in gfc */\n\nvoid\nfree_id3tag(lame_internal_flags * const gfc)\n{\n    if (gfc->tag_spec.title != 0) {\n        free(gfc->tag_spec.title);\n        gfc->tag_spec.title = 0;\n    }\n    if (gfc->tag_spec.artist != 0) {\n        free(gfc->tag_spec.artist);\n        gfc->tag_spec.artist = 0;\n    }\n    if (gfc->tag_spec.album != 0) {\n        free(gfc->tag_spec.album);\n        gfc->tag_spec.album = 0;\n    }\n    if (gfc->tag_spec.comment != 0) {\n        free(gfc->tag_spec.comment);\n        gfc->tag_spec.comment = 0;\n    }\n\n    if (gfc->tag_spec.albumart != 0) {\n        free(gfc->tag_spec.albumart);\n        gfc->tag_spec.albumart = 0;\n        gfc->tag_spec.albumart_size = 0;\n        gfc->tag_spec.albumart_mimetype = MIMETYPE_NONE;\n    }\n    if (gfc->tag_spec.v2_head != 0) {\n        FrameDataNode *node = gfc->tag_spec.v2_head;\n        do {\n            void   *p = node->dsc.ptr.b;\n            void   *q = node->txt.ptr.b;\n            void   *r = node;\n            node = node->nxt;\n            free(p);\n            free(q);\n            free(r);\n        } while (node != 0);\n        gfc->tag_spec.v2_head = 0;\n        gfc->tag_spec.v2_tail = 0;\n    }\n}\n\n\nstatic void\nfree_global_data(lame_internal_flags * gfc)\n{\n    if (gfc && gfc->cd_psy) {\n        if (gfc->cd_psy->l.s3) {\n            /* XXX allocated in psymodel_init() */\n            free(gfc->cd_psy->l.s3);\n        }\n        if (gfc->cd_psy->s.s3) {\n            /* XXX allocated in psymodel_init() */\n            free(gfc->cd_psy->s.s3);\n        }\n        free(gfc->cd_psy);\n        gfc->cd_psy = 0;\n    }\n}\n\n\nvoid\nfreegfc(lame_internal_flags * const gfc)\n{                       /* bit stream structure */\n    int     i;\n\n\n    for (i = 0; i <= 2 * BPC; i++)\n        if (gfc->sv_enc.blackfilt[i] != NULL) {\n            free(gfc->sv_enc.blackfilt[i]);\n            gfc->sv_enc.blackfilt[i] = NULL;\n        }\n    if (gfc->sv_enc.inbuf_old[0]) {\n        free(gfc->sv_enc.inbuf_old[0]);\n        gfc->sv_enc.inbuf_old[0] = NULL;\n    }\n    if (gfc->sv_enc.inbuf_old[1]) {\n        free(gfc->sv_enc.inbuf_old[1]);\n        gfc->sv_enc.inbuf_old[1] = NULL;\n    }\n\n    if (gfc->bs.buf != NULL) {\n        free(gfc->bs.buf);\n        gfc->bs.buf = NULL;\n    }\n\n    if (gfc->VBR_seek_table.bag) {\n        free(gfc->VBR_seek_table.bag);\n        gfc->VBR_seek_table.bag = NULL;\n        gfc->VBR_seek_table.size = 0;\n    }\n    if (gfc->ATH) {\n        free(gfc->ATH);\n    }\n    if (gfc->sv_rpg.rgdata) {\n        free(gfc->sv_rpg.rgdata);\n    }\n    if (gfc->sv_enc.in_buffer_0) {\n        free(gfc->sv_enc.in_buffer_0);\n    }\n    if (gfc->sv_enc.in_buffer_1) {\n        free(gfc->sv_enc.in_buffer_1);\n    }\n    free_id3tag(gfc);\n\n#ifdef DECODE_ON_THE_FLY\n    if (gfc->hip) {\n        hip_decode_exit(gfc->hip);\n        gfc->hip = 0;\n    }\n#endif\n\n    free_global_data(gfc);\n\n    free(gfc);\n}\n\nvoid\nmalloc_aligned(aligned_pointer_t * ptr, unsigned int size, unsigned int bytes)\n{\n    if (ptr) {\n        if (!ptr->pointer) {\n            ptr->pointer = malloc(size + bytes);\n            if (bytes > 0) {\n                ptr->aligned = (void *) ((((size_t) ptr->pointer + bytes - 1) / bytes) * bytes);\n            }\n            else {\n                ptr->aligned = ptr->pointer;\n            }\n        }\n    }\n}\n\nvoid\nfree_aligned(aligned_pointer_t * ptr)\n{\n    if (ptr) {\n        if (ptr->pointer) {\n            free(ptr->pointer);\n            ptr->pointer = 0;\n            ptr->aligned = 0;\n        }\n    }\n}\n\n/*those ATH formulas are returning\ntheir minimum value for input = -1*/\n\nstatic  FLOAT\nATHformula_GB(FLOAT f, FLOAT value, FLOAT f_min, FLOAT f_max)\n{\n    /* from Painter & Spanias\n       modified by Gabriel Bouvigne to better fit the reality\n       ath =    3.640 * pow(f,-0.8)\n       - 6.800 * exp(-0.6*pow(f-3.4,2.0))\n       + 6.000 * exp(-0.15*pow(f-8.7,2.0))\n       + 0.6* 0.001 * pow(f,4.0);\n\n\n       In the past LAME was using the Painter &Spanias formula.\n       But we had some recurrent problems with HF content.\n       We measured real ATH values, and found the older formula\n       to be inacurate in the higher part. So we made this new\n       formula and this solved most of HF problematic testcases.\n       The tradeoff is that in VBR mode it increases a lot the\n       bitrate. */\n\n\n/*this curve can be udjusted according to the VBR scale:\nit adjusts from something close to Painter & Spanias\non V9 up to Bouvigne's formula for V0. This way the VBR\nbitrate is more balanced according to the -V value.*/\n\n    FLOAT   ath;\n\n    /* the following Hack allows to ask for the lowest value */\n    if (f < -.3)\n        f = 3410;\n\n    f /= 1000;          /* convert to khz */\n    f = Max(f_min, f);\n    f = Min(f_max, f);\n\n    ath = 3.640 * pow(f, -0.8)\n        - 6.800 * exp(-0.6 * pow(f - 3.4, 2.0))\n        + 6.000 * exp(-0.15 * pow(f - 8.7, 2.0))\n        + (0.6 + 0.04 * value) * 0.001 * pow(f, 4.0);\n    return ath;\n}\n\n\n\nFLOAT\nATHformula(SessionConfig_t const *cfg, FLOAT f)\n{\n    FLOAT   ath;\n    switch (cfg->ATHtype) {\n    case 0:\n        ath = ATHformula_GB(f, 9, 0.1f, 24.0f);\n        break;\n    case 1:\n        ath = ATHformula_GB(f, -1, 0.1f, 24.0f); /*over sensitive, should probably be removed */\n        break;\n    case 2:\n        ath = ATHformula_GB(f, 0, 0.1f, 24.0f);\n        break;\n    case 3:\n        ath = ATHformula_GB(f, 1, 0.1f, 24.0f) + 6; /*modification of GB formula by Roel */\n        break;\n    case 4:\n        ath = ATHformula_GB(f, cfg->ATHcurve, 0.1f, 24.0f);\n        break;\n    case 5:\n        ath = ATHformula_GB(f, cfg->ATHcurve, 3.41f, 16.1f);\n        break;\n    default:\n        ath = ATHformula_GB(f, 0, 0.1f, 24.0f);\n        break;\n    }\n    return ath;\n}\n\n/* see for example \"Zwicker: Psychoakustik, 1982; ISBN 3-540-11401-7 */\nFLOAT\nfreq2bark(FLOAT freq)\n{\n    /* input: freq in hz  output: barks */\n    if (freq < 0)\n        freq = 0;\n    freq = freq * 0.001;\n    return 13.0 * atan(.76 * freq) + 3.5 * atan(freq * freq / (7.5 * 7.5));\n}\n\n#if 0\nextern FLOAT freq2cbw(FLOAT freq);\n\n/* see for example \"Zwicker: Psychoakustik, 1982; ISBN 3-540-11401-7 */\nFLOAT\nfreq2cbw(FLOAT freq)\n{\n    /* input: freq in hz  output: critical band width */\n    freq = freq * 0.001;\n    return 25 + 75 * pow(1 + 1.4 * (freq * freq), 0.69);\n}\n\n#endif\n\n\n\n\n#define ABS(A) (((A)>0) ? (A) : -(A))\n\nint\nFindNearestBitrate(int bRate, /* legal rates from 8 to 320 */\n                   int version, int samplerate)\n{                       /* MPEG-1 or MPEG-2 LSF */\n    int     bitrate;\n    int     i;\n\n    if (samplerate < 16000)\n        version = 2;\n\n    bitrate = bitrate_table[version][1];\n\n    for (i = 2; i <= 14; i++) {\n        if (bitrate_table[version][i] > 0) {\n            if (ABS(bitrate_table[version][i] - bRate) < ABS(bitrate - bRate))\n                bitrate = bitrate_table[version][i];\n        }\n    }\n    return bitrate;\n}\n\n\n\n\n\n#ifndef Min\n#define         Min(A, B)       ((A) < (B) ? (A) : (B))\n#endif\n#ifndef Max\n#define         Max(A, B)       ((A) > (B) ? (A) : (B))\n#endif\n\n\n/* Used to find table index when\n * we need bitrate-based values\n * determined using tables\n *\n * bitrate in kbps\n *\n * Gabriel Bouvigne 2002-11-03\n */\nint\nnearestBitrateFullIndex(uint16_t bitrate)\n{\n    /* borrowed from DM abr presets */\n\n    const int full_bitrate_table[] =\n        { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 };\n\n\n    int     lower_range = 0, lower_range_kbps = 0, upper_range = 0, upper_range_kbps = 0;\n\n\n    int     b;\n\n\n    /* We assume specified bitrate will be 320kbps */\n    upper_range_kbps = full_bitrate_table[16];\n    upper_range = 16;\n    lower_range_kbps = full_bitrate_table[16];\n    lower_range = 16;\n\n    /* Determine which significant bitrates the value specified falls between,\n     * if loop ends without breaking then we were correct above that the value was 320\n     */\n    for (b = 0; b < 16; b++) {\n        if ((Max(bitrate, full_bitrate_table[b + 1])) != bitrate) {\n            upper_range_kbps = full_bitrate_table[b + 1];\n            upper_range = b + 1;\n            lower_range_kbps = full_bitrate_table[b];\n            lower_range = (b);\n            break;      /* We found upper range */\n        }\n    }\n\n    /* Determine which range the value specified is closer to */\n    if ((upper_range_kbps - bitrate) > (bitrate - lower_range_kbps)) {\n        return lower_range;\n    }\n    return upper_range;\n}\n\n\n\n\n\n/* map frequency to a valid MP3 sample frequency\n *\n * Robert Hegemann 2000-07-01\n */\nint\nmap2MP3Frequency(int freq)\n{\n    if (freq <= 8000)\n        return 8000;\n    if (freq <= 11025)\n        return 11025;\n    if (freq <= 12000)\n        return 12000;\n    if (freq <= 16000)\n        return 16000;\n    if (freq <= 22050)\n        return 22050;\n    if (freq <= 24000)\n        return 24000;\n    if (freq <= 32000)\n        return 32000;\n    if (freq <= 44100)\n        return 44100;\n\n    return 48000;\n}\n\nint\nBitrateIndex(int bRate,      /* legal rates from 32 to 448 kbps */\n             int version,    /* MPEG-1 or MPEG-2/2.5 LSF */\n             int samplerate)\n{                       /* convert bitrate in kbps to index */\n    int     i;\n    if (samplerate < 16000)\n        version = 2;\n    for (i = 0; i <= 14; i++) {\n        if (bitrate_table[version][i] > 0) {\n            if (bitrate_table[version][i] == bRate) {\n                return i;\n            }\n        }\n    }\n    return -1;\n}\n\n/* convert samp freq in Hz to index */\n\nint\nSmpFrqIndex(int sample_freq, int *const version)\n{\n    switch (sample_freq) {\n    case 44100:\n        *version = 1;\n        return 0;\n    case 48000:\n        *version = 1;\n        return 1;\n    case 32000:\n        *version = 1;\n        return 2;\n    case 22050:\n        *version = 0;\n        return 0;\n    case 24000:\n        *version = 0;\n        return 1;\n    case 16000:\n        *version = 0;\n        return 2;\n    case 11025:\n        *version = 0;\n        return 0;\n    case 12000:\n        *version = 0;\n        return 1;\n    case 8000:\n        *version = 0;\n        return 2;\n    default:\n        *version = 0;\n        return -1;\n    }\n}\n\n\n/*****************************************************************************\n*\n*  End of bit_stream.c package\n*\n*****************************************************************************/\n\n\n\n\n\n\n\n\n\n\n/* resampling via FIR filter, blackman window */\ninline static FLOAT\nblackman(FLOAT x, FLOAT fcn, int l)\n{\n    /* This algorithm from:\n       SIGNAL PROCESSING ALGORITHMS IN FORTRAN AND C\n       S.D. Stearns and R.A. David, Prentice-Hall, 1992\n     */\n    FLOAT   bkwn, x2;\n    FLOAT const wcn = (PI * fcn);\n\n    x /= l;\n    if (x < 0)\n        x = 0;\n    if (x > 1)\n        x = 1;\n    x2 = x - .5;\n\n    bkwn = 0.42 - 0.5 * cos(2 * x * PI) + 0.08 * cos(4 * x * PI);\n    if (fabs(x2) < 1e-9)\n        return wcn / PI;\n    else\n        return (bkwn * sin(l * wcn * x2) / (PI * l * x2));\n\n\n}\n\n\n\n\n/* gcd - greatest common divisor */\n/* Joint work of Euclid and M. Hendry */\n\nstatic int\ngcd(int i, int j)\n{\n    /*    assert ( i > 0  &&  j > 0 ); */\n    return j ? gcd(j, i % j) : i;\n}\n\n\n\nstatic int\nfill_buffer_resample(lame_internal_flags * gfc,\n                     sample_t * outbuf,\n                     int desired_len, sample_t const *inbuf, int len, int *num_used, int ch)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    EncStateVar_t *esv = &gfc->sv_enc;\n    double  resample_ratio = (double)cfg->samplerate_in / (double)cfg->samplerate_out;\n    int     BLACKSIZE;\n    FLOAT   offset, xvalue;\n    int     i, j = 0, k;\n    int     filter_l;\n    FLOAT   fcn, intratio;\n    FLOAT  *inbuf_old;\n    int     bpc;             /* number of convolution functions to pre-compute */\n    bpc = cfg->samplerate_out / gcd(cfg->samplerate_out, cfg->samplerate_in);\n    if (bpc > BPC)\n        bpc = BPC;\n\n    intratio = (fabs(resample_ratio - floor(.5 + resample_ratio)) < .0001);\n    fcn = 1.00 / resample_ratio;\n    if (fcn > 1.00)\n        fcn = 1.00;\n    filter_l = 31;     /* must be odd */\n    filter_l += intratio; /* unless resample_ratio=int, it must be even */\n\n\n    BLACKSIZE = filter_l + 1; /* size of data needed for FIR */\n\n    if (gfc->fill_buffer_resample_init == 0) {\n        esv->inbuf_old[0] = calloc(BLACKSIZE, sizeof(esv->inbuf_old[0][0]));\n        esv->inbuf_old[1] = calloc(BLACKSIZE, sizeof(esv->inbuf_old[0][0]));\n        for (i = 0; i <= 2 * bpc; ++i)\n            esv->blackfilt[i] = calloc(BLACKSIZE, sizeof(esv->blackfilt[0][0]));\n\n        esv->itime[0] = 0;\n        esv->itime[1] = 0;\n\n        /* precompute blackman filter coefficients */\n        for (j = 0; j <= 2 * bpc; j++) {\n            FLOAT   sum = 0.;\n            offset = (j - bpc) / (2. * bpc);\n            for (i = 0; i <= filter_l; i++)\n                sum += esv->blackfilt[j][i] = blackman(i - offset, fcn, filter_l);\n            for (i = 0; i <= filter_l; i++)\n                esv->blackfilt[j][i] /= sum;\n        }\n        gfc->fill_buffer_resample_init = 1;\n    }\n\n    inbuf_old = esv->inbuf_old[ch];\n\n    /* time of j'th element in inbuf = itime + j/ifreq; */\n    /* time of k'th element in outbuf   =  j/ofreq */\n    for (k = 0; k < desired_len; k++) {\n        double  time0 = k * resample_ratio; /* time of k'th output sample */\n        int     joff;\n\n        j = floor(time0 - esv->itime[ch]);\n\n        /* check if we need more input data */\n        if ((filter_l + j - filter_l / 2) >= len)\n            break;\n\n        /* blackman filter.  by default, window centered at j+.5(filter_l%2) */\n        /* but we want a window centered at time0.   */\n        offset = (time0 - esv->itime[ch] - (j + .5 * (filter_l % 2)));\n        assert(fabs(offset) <= .501);\n\n        /* find the closest precomputed window for this offset: */\n        joff = floor((offset * 2 * bpc) + bpc + .5);\n\n        xvalue = 0.;\n        for (i = 0; i <= filter_l; ++i) {\n            int const j2 = i + j - filter_l / 2;\n            sample_t y;\n            assert(j2 < len);\n            assert(j2 + BLACKSIZE >= 0);\n            y = (j2 < 0) ? inbuf_old[BLACKSIZE + j2] : inbuf[j2];\n#ifdef PRECOMPUTE\n            xvalue += y * esv->blackfilt[joff][i];\n#else\n            xvalue += y * blackman(i - offset, fcn, filter_l); /* very slow! */\n#endif\n        }\n        outbuf[k] = xvalue;\n    }\n\n\n    /* k = number of samples added to outbuf */\n    /* last k sample used data from [j-filter_l/2,j+filter_l-filter_l/2]  */\n\n    /* how many samples of input data were used:  */\n    *num_used = Min(len, filter_l + j - filter_l / 2);\n\n    /* adjust our input time counter.  Incriment by the number of samples used,\n     * then normalize so that next output sample is at time 0, next\n     * input buffer is at time itime[ch] */\n    esv->itime[ch] += *num_used - k * resample_ratio;\n\n    /* save the last BLACKSIZE samples into the inbuf_old buffer */\n    if (*num_used >= BLACKSIZE) {\n        for (i = 0; i < BLACKSIZE; i++)\n            inbuf_old[i] = inbuf[*num_used + i - BLACKSIZE];\n    }\n    else {\n        /* shift in *num_used samples into inbuf_old  */\n        int const n_shift = BLACKSIZE - *num_used; /* number of samples to shift */\n\n        /* shift n_shift samples by *num_used, to make room for the\n         * num_used new samples */\n        for (i = 0; i < n_shift; ++i)\n            inbuf_old[i] = inbuf_old[i + *num_used];\n\n        /* shift in the *num_used samples */\n        for (j = 0; i < BLACKSIZE; ++i, ++j)\n            inbuf_old[i] = inbuf[j];\n\n        assert(j == *num_used);\n    }\n    return k;           /* return the number samples created at the new samplerate */\n}\n\nint\nisResamplingNecessary(SessionConfig_t const* cfg)\n{\n    int const l = cfg->samplerate_out * 0.9995f;\n    int const h = cfg->samplerate_out * 1.0005f;\n    return (cfg->samplerate_in < l) || (h < cfg->samplerate_in) ? 1 : 0;\n}\n\n/* copy in new samples from in_buffer into mfbuf, with resampling\n   if necessary.  n_in = number of samples from the input buffer that\n   were used.  n_out = number of samples copied into mfbuf  */\n\nvoid\nfill_buffer(lame_internal_flags * gfc,\n            sample_t * const mfbuf[2], sample_t const * const in_buffer[2], int nsamples, int *n_in, int *n_out)\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     mf_size = gfc->sv_enc.mf_size;\n    int     framesize = 576 * cfg->mode_gr;\n    int     nout, ch = 0;\n    int     nch = cfg->channels_out;\n\n    /* copy in new samples into mfbuf, with resampling if necessary */\n    if (isResamplingNecessary(cfg)) {\n        do {\n            nout =\n                fill_buffer_resample(gfc, &mfbuf[ch][mf_size],\n                                     framesize, in_buffer[ch], nsamples, n_in, ch);\n        } while (++ch < nch);\n        *n_out = nout;\n    }\n    else {\n        nout = Min(framesize, nsamples);\n        do {\n            memcpy(&mfbuf[ch][mf_size], &in_buffer[ch][0], nout * sizeof(mfbuf[0][0]));\n        } while (++ch < nch);\n        *n_out = nout;\n        *n_in = nout;\n    }\n}\n\n\n\n\n\n\n\n/***********************************************************************\n*\n*  Message Output\n*\n***********************************************************************/\n\nvoid\nlame_report_def(const char *format, va_list args)\n{\n    (void) vfprintf(stderr, format, args);\n    fflush(stderr); /* an debug function should flush immediately */\n}\n\nvoid \nlame_report_fnc(lame_report_function print_f, const char *format, ...)\n{\n    if (print_f) {\n        va_list args;\n        va_start(args, format);\n        print_f(format, args);\n        va_end(args);\n    }\n}\n\n\nvoid\nlame_debugf(const lame_internal_flags* gfc, const char *format, ...)\n{\n    if (gfc && gfc->report_dbg) {\n        va_list args;\n        va_start(args, format);\n        gfc->report_dbg(format, args);\n        va_end(args);\n    }\n}\n\n\nvoid\nlame_msgf(const lame_internal_flags* gfc, const char *format, ...)\n{\n    if (gfc && gfc->report_msg) {\n        va_list args;\n        va_start(args, format);\n        gfc->report_msg(format, args);\n        va_end(args);\n    }\n}\n\n\nvoid\nlame_errorf(const lame_internal_flags* gfc, const char *format, ...)\n{\n    if (gfc && gfc->report_err) {\n        va_list args;\n        va_start(args, format);\n        gfc->report_err(format, args);\n        va_end(args);\n    }\n}\n\n\n\n/***********************************************************************\n *\n *      routines to detect CPU specific features like 3DNow, MMX, SSE\n *\n *  donated by Frank Klemm\n *  added Robert Hegemann 2000-10-10\n *\n ***********************************************************************/\n\n#ifdef HAVE_NASM\nextern int has_MMX_nasm(void);\nextern int has_3DNow_nasm(void);\nextern int has_SSE_nasm(void);\nextern int has_SSE2_nasm(void);\n#endif\n\nint\nhas_MMX(void)\n{\n#ifdef HAVE_NASM\n    return has_MMX_nasm();\n#else\n    return 0;           /* don't know, assume not */\n#endif\n}\n\nint\nhas_3DNow(void)\n{\n#ifdef HAVE_NASM\n    return has_3DNow_nasm();\n#else\n    return 0;           /* don't know, assume not */\n#endif\n}\n\nint\nhas_SSE(void)\n{\n#ifdef HAVE_NASM\n    return has_SSE_nasm();\n#else\n#if defined( _M_X64 ) || defined( MIN_ARCH_SSE )\n    return 1;\n#else\n    return 0;           /* don't know, assume not */\n#endif\n#endif\n}\n\nint\nhas_SSE2(void)\n{\n#ifdef HAVE_NASM\n    return has_SSE2_nasm();\n#else\n#if defined( _M_X64 ) || defined( MIN_ARCH_SSE )\n    return 1;\n#else\n    return 0;           /* don't know, assume not */\n#endif\n#endif\n}\n\nvoid\ndisable_FPE(void)\n{\n/* extremly system dependent stuff, move to a lib to make the code readable */\n/*==========================================================================*/\n\n\n\n    /*\n     *  Disable floating point exceptions\n     */\n\n\n\n\n#if defined(__FreeBSD__) && !defined(__alpha__)\n    {\n        /* seet floating point mask to the Linux default */\n        fp_except_t mask;\n        mask = fpgetmask();\n        /* if bit is set, we get SIGFPE on that error! */\n        fpsetmask(mask & ~(FP_X_INV | FP_X_DZ));\n        /*  DEBUGF(\"FreeBSD mask is 0x%x\\n\",mask); */\n    }\n#endif\n\n#if defined(__riscos__) && !defined(ABORTFP)\n    /* Disable FPE's under RISC OS */\n    /* if bit is set, we disable trapping that error! */\n    /*   _FPE_IVO : invalid operation */\n    /*   _FPE_DVZ : divide by zero */\n    /*   _FPE_OFL : overflow */\n    /*   _FPE_UFL : underflow */\n    /*   _FPE_INX : inexact */\n    DisableFPETraps(_FPE_IVO | _FPE_DVZ | _FPE_OFL);\n#endif\n\n    /*\n     *  Debugging stuff\n     *  The default is to ignore FPE's, unless compiled with -DABORTFP\n     *  so add code below to ENABLE FPE's.\n     */\n\n#if defined(ABORTFP)\n#if defined(_MSC_VER)\n    {\n#if 0\n        /* rh 061207\n           the following fix seems to be a workaround for a problem in the\n           parent process calling LAME. It would be better to fix the broken\n           application => code disabled.\n         */\n\n        /* set affinity to a single CPU.  Fix for EAC/lame on SMP systems from\n           \"Todd Richmond\" <todd.richmond@openwave.com> */\n        SYSTEM_INFO si;\n        GetSystemInfo(&si);\n        SetProcessAffinityMask(GetCurrentProcess(), si.dwActiveProcessorMask);\n#endif\n#include <float.h>\n        unsigned int mask;\n        mask = _controlfp(0, 0);\n        mask &= ~(_EM_OVERFLOW | _EM_UNDERFLOW | _EM_ZERODIVIDE | _EM_INVALID);\n        mask = _controlfp(mask, _MCW_EM);\n    }\n#elif defined(__CYGWIN__)\n#  define _FPU_GETCW(cw) __asm__ (\"fnstcw %0\" : \"=m\" (*&cw))\n#  define _FPU_SETCW(cw) __asm__ (\"fldcw %0\" : : \"m\" (*&cw))\n\n#  define _EM_INEXACT     0x00000020 /* inexact (precision) */\n#  define _EM_UNDERFLOW   0x00000010 /* underflow */\n#  define _EM_OVERFLOW    0x00000008 /* overflow */\n#  define _EM_ZERODIVIDE  0x00000004 /* zero divide */\n#  define _EM_INVALID     0x00000001 /* invalid */\n    {\n        unsigned int mask;\n        _FPU_GETCW(mask);\n        /* Set the FPU control word to abort on most FPEs */\n        mask &= ~(_EM_OVERFLOW | _EM_ZERODIVIDE | _EM_INVALID);\n        _FPU_SETCW(mask);\n    }\n# elif defined(__linux__)\n    {\n\n#  include <fpu_control.h>\n#  ifndef _FPU_GETCW\n#  define _FPU_GETCW(cw) __asm__ (\"fnstcw %0\" : \"=m\" (*&cw))\n#  endif\n#  ifndef _FPU_SETCW\n#  define _FPU_SETCW(cw) __asm__ (\"fldcw %0\" : : \"m\" (*&cw))\n#  endif\n\n        /* \n         * Set the Linux mask to abort on most FPE's\n         * if bit is set, we _mask_ SIGFPE on that error!\n         *  mask &= ~( _FPU_MASK_IM | _FPU_MASK_ZM | _FPU_MASK_OM | _FPU_MASK_UM );\n         */\n\n        unsigned int mask;\n        _FPU_GETCW(mask);\n        mask &= ~(_FPU_MASK_IM | _FPU_MASK_ZM | _FPU_MASK_OM);\n        _FPU_SETCW(mask);\n    }\n#endif\n#endif /* ABORTFP */\n}\n\n\n\n\n\n#ifdef USE_FAST_LOG\n/***********************************************************************\n *\n * Fast Log Approximation for log2, used to approximate every other log\n * (log10 and log)\n * maximum absolute error for log10 is around 10-6\n * maximum *relative* error can be high when x is almost 1 because error/log10(x) tends toward x/e\n *\n * use it if typical RESULT values are > 1e-5 (for example if x>1.00001 or x<0.99999)\n * or if the relative precision in the domain around 1 is not important (result in 1 is exact and 0)\n *\n ***********************************************************************/\n\n\n#define LOG2_SIZE       (512)\n#define LOG2_SIZE_L2    (9)\n\nstatic ieee754_float32_t log_table[LOG2_SIZE + 1];\n\n\n\nvoid\ninit_log_table(void)\n{\n    int     j;\n    static int init = 0;\n\n    /* Range for log2(x) over [1,2[ is [0,1[ */\n    assert((1 << LOG2_SIZE_L2) == LOG2_SIZE);\n\n    if (!init) {\n        for (j = 0; j < LOG2_SIZE + 1; j++)\n            log_table[j] = log(1.0f + j / (ieee754_float32_t) LOG2_SIZE) / log(2.0f);\n    }\n    init = 1;\n}\n\n\n\nieee754_float32_t\nfast_log2(ieee754_float32_t x)\n{\n    ieee754_float32_t log2val, partial;\n    union {\n        ieee754_float32_t f;\n        int     i;\n    } fi;\n    int     mantisse;\n    fi.f = x;\n    mantisse = fi.i & 0x7fffff;\n    log2val = ((fi.i >> 23) & 0xFF) - 0x7f;\n    partial = (mantisse & ((1 << (23 - LOG2_SIZE_L2)) - 1));\n    partial *= 1.0f / ((1 << (23 - LOG2_SIZE_L2)));\n\n\n    mantisse >>= (23 - LOG2_SIZE_L2);\n\n    /* log2val += log_table[mantisse];  without interpolation the results are not good */\n    log2val += log_table[mantisse] * (1.0f - partial) + log_table[mantisse + 1] * partial;\n\n    return log2val;\n}\n\n#else /* Don't use FAST_LOG */\n\n\nvoid\ninit_log_table(void)\n{\n}\n\n\n#endif\n\n/* end of util.c */\n"
  },
  {
    "path": "app/jni/libmp3lame/util.h",
    "content": "/*\n *      lame utility library include file\n *\n *      Copyright (c) 1999 Albert L Faber\n *      Copyright (c) 2008 Robert Hegemann\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_UTIL_H\n#define LAME_UTIL_H\n\n#include \"l3side.h\"\n#include \"id3tag.h\"\n#include \"lame_global_flags.h\"\n\n#ifdef __cplusplus\nextern  \"C\" {\n#endif\n\n/***********************************************************************\n*\n*  Global Definitions\n*\n***********************************************************************/\n\n#ifndef FALSE\n#define         FALSE                   0\n#endif\n\n#ifndef TRUE\n#define         TRUE                    (!FALSE)\n#endif\n\n#ifdef UINT_MAX\n# define         MAX_U_32_NUM            UINT_MAX\n#else\n# define         MAX_U_32_NUM            0xFFFFFFFF\n#endif\n\n#ifndef PI\n# ifdef M_PI\n#  define       PI                      M_PI\n# else\n#  define       PI                      3.14159265358979323846\n# endif\n#endif\n\n\n#ifdef M_LN2\n# define        LOG2                    M_LN2\n#else\n# define        LOG2                    0.69314718055994530942\n#endif\n\n#ifdef M_LN10\n# define        LOG10                   M_LN10\n#else\n# define        LOG10                   2.30258509299404568402\n#endif\n\n\n#ifdef M_SQRT2\n# define        SQRT2                   M_SQRT2\n#else\n# define        SQRT2                   1.41421356237309504880\n#endif\n\n\n#define         CRC16_POLYNOMIAL        0x8005\n\n#define MAX_BITS_PER_CHANNEL 4095\n#define MAX_BITS_PER_GRANULE 7680\n\n/* \"bit_stream.h\" Definitions */\n#define         BUFFER_SIZE     LAME_MAXMP3BUFFER\n\n#define         Min(A, B)       ((A) < (B) ? (A) : (B))\n#define         Max(A, B)       ((A) > (B) ? (A) : (B))\n\n/* log/log10 approximations */\n#ifdef USE_FAST_LOG\n#define         FAST_LOG10(x)       (fast_log2(x)*(LOG2/LOG10))\n#define         FAST_LOG(x)         (fast_log2(x)*LOG2)\n#define         FAST_LOG10_X(x,y)   (fast_log2(x)*(LOG2/LOG10*(y)))\n#define         FAST_LOG_X(x,y)     (fast_log2(x)*(LOG2*(y)))\n#else\n#define         FAST_LOG10(x)       log10(x)\n#define         FAST_LOG(x)         log(x)\n#define         FAST_LOG10_X(x,y)   (log10(x)*(y))\n#define         FAST_LOG_X(x,y)     (log(x)*(y))\n#endif\n\n\n    struct replaygain_data;\n#ifndef replaygain_data_defined\n#define replaygain_data_defined\n    typedef struct replaygain_data replaygain_t;\n#endif\n    struct plotting_data;\n#ifndef plotting_data_defined\n#define plotting_data_defined\n    typedef struct plotting_data plotting_data;\n#endif\n\n/***********************************************************************\n*\n*  Global Type Definitions\n*\n***********************************************************************/\n\n    typedef struct {\n        void   *aligned;     /* pointer to ie. 128 bit aligned memory */\n        void   *pointer;     /* to use with malloc/free */\n    } aligned_pointer_t;\n\n    void    malloc_aligned(aligned_pointer_t * ptr, unsigned int size, unsigned int bytes);\n    void    free_aligned(aligned_pointer_t * ptr);\n\n\n    typedef void (*iteration_loop_t) (lame_internal_flags * gfc, const FLOAT pe[2][2],\n                                      const FLOAT ms_ratio[2], const III_psy_ratio ratio[2][2]);\n\n\n    /* \"bit_stream.h\" Type Definitions */\n\n    typedef struct bit_stream_struc {\n        unsigned char *buf;  /* bit stream buffer */\n        int     buf_size;    /* size of buffer (in number of bytes) */\n        int     totbit;      /* bit counter of bit stream */\n        int     buf_byte_idx; /* pointer to top byte in buffer */\n        int     buf_bit_idx; /* pointer to top bit of top byte in buffer */\n\n        /* format of file in rd mode (BINARY/ASCII) */\n    } Bit_stream_struc;\n\n\n\n    typedef struct {\n        int     sum;         /* what we have seen so far */\n        int     seen;        /* how many frames we have seen in this chunk */\n        int     want;        /* how many frames we want to collect into one chunk */\n        int     pos;         /* actual position in our bag */\n        int     size;        /* size of our bag */\n        int    *bag;         /* pointer to our bag */\n        unsigned int nVbrNumFrames;\n        unsigned long nBytesWritten;\n        /* VBR tag data */\n        unsigned int TotalFrameSize;\n    } VBR_seek_info_t;\n\n\n    /**\n     *  ATH related stuff, if something new ATH related has to be added,\n     *  please plugg it here into the ATH_t struct\n     */\n    typedef struct {\n        int     use_adjust;  /* method for the auto adjustment  */\n        FLOAT   aa_sensitivity_p; /* factor for tuning the (sample power)\n                                     point below which adaptive threshold\n                                     of hearing adjustment occurs */\n        FLOAT   adjust_factor; /* lowering based on peak volume, 1 = no lowering */\n        FLOAT   adjust_limit; /* limit for dynamic ATH adjust */\n        FLOAT   decay;       /* determined to lower x dB each second */\n        FLOAT   floor;       /* lowest ATH value */\n        FLOAT   l[SBMAX_l];  /* ATH for sfbs in long blocks */\n        FLOAT   s[SBMAX_s];  /* ATH for sfbs in short blocks */\n        FLOAT   psfb21[PSFB21]; /* ATH for partitionned sfb21 in long blocks */\n        FLOAT   psfb12[PSFB12]; /* ATH for partitionned sfb12 in short blocks */\n        FLOAT   cb_l[CBANDS]; /* ATH for long block convolution bands */\n        FLOAT   cb_s[CBANDS]; /* ATH for short block convolution bands */\n        FLOAT   eql_w[BLKSIZE / 2]; /* equal loudness weights (based on ATH) */\n    } ATH_t;\n\n    /**\n     *  PSY Model related stuff\n     */\n\n    typedef struct {\n        FLOAT   masking_lower[CBANDS];\n        FLOAT   minval[CBANDS];\n        FLOAT   rnumlines[CBANDS];\n        FLOAT   mld_cb[CBANDS];\n        FLOAT   mld[Max(SBMAX_l,SBMAX_s)];\n        FLOAT   bo_weight[Max(SBMAX_l,SBMAX_s)]; /* band weight long scalefactor bands, at transition */\n        FLOAT   attack_threshold; /* short block tuning */\n        int     s3ind[CBANDS][2];\n        int     numlines[CBANDS];\n        int     bm[Max(SBMAX_l,SBMAX_s)];\n        int     bo[Max(SBMAX_l,SBMAX_s)];\n        int     npart;\n        int     n_sb; /* SBMAX_l or SBMAX_s */\n        FLOAT  *s3;\n    } PsyConst_CB2SB_t;\n\n\n    /**\n     *  global data constants\n     */\n    typedef struct {\n        PsyConst_CB2SB_t l;\n        PsyConst_CB2SB_t s;\n        PsyConst_CB2SB_t l_to_s;\n        FLOAT   attack_threshold[4];\n        FLOAT   decay;\n        int     force_short_block_calc;\n    } PsyConst_t;\n\n\n    typedef struct {\n\n        FLOAT   nb_l1[4][CBANDS], nb_l2[4][CBANDS];\n        FLOAT   nb_s1[4][CBANDS], nb_s2[4][CBANDS];\n\n        III_psy_xmin thm[4];\n        III_psy_xmin en[4];\n\n        /* loudness calculation (for adaptive threshold of hearing) */\n        FLOAT   loudness_sq_save[2]; /* account for granule delay of L3psycho_anal */\n\n        FLOAT   tot_ener[4];\n\n        FLOAT   last_en_subshort[4][9];\n        int     last_attacks[4];\n\n        int     blocktype_old[2];\n    } PsyStateVar_t;\n\n\n    typedef struct {\n        /* loudness calculation (for adaptive threshold of hearing) */\n        FLOAT   loudness_sq[2][2]; /* loudness^2 approx. per granule and channel */\n    } PsyResult_t;\n\n\n    /* variables used by encoder.c */\n    typedef struct {\n        /* variables for newmdct.c */\n        FLOAT   sb_sample[2][2][18][SBLIMIT];\n        FLOAT   amp_filter[32];\n\n        /* variables used by util.c */\n        /* BPC = maximum number of filter convolution windows to precompute */\n#define BPC 320\n        double  itime[2]; /* float precision seems to be not enough */\n        sample_t *inbuf_old[2];\n        sample_t *blackfilt[2 * BPC + 1];\n\n        FLOAT   pefirbuf[19];\n        \n        /* used for padding */\n        int     frac_SpF;\n        int     slot_lag;\n\n        /* variables for bitstream.c */\n        /* mpeg1: buffer=511 bytes  smallest frame: 96-38(sideinfo)=58\n         * max number of frames in reservoir:  8\n         * mpeg2: buffer=255 bytes.  smallest frame: 24-23bytes=1\n         * with VBR, if you are encoding all silence, it is possible to\n         * have 8kbs/24khz frames with 1byte of data each, which means we need\n         * to buffer up to 255 headers! */\n        /* also, max_header_buf has to be a power of two */\n#define MAX_HEADER_BUF 256\n#define MAX_HEADER_LEN 40    /* max size of header is 38 */\n        struct {\n            int     write_timing;\n            int     ptr;\n            char    buf[MAX_HEADER_LEN];\n        } header[MAX_HEADER_BUF];\n\n        int     h_ptr;\n        int     w_ptr;\n        int     ancillary_flag;\n\n        /* variables for reservoir.c */\n        int     ResvSize;    /* in bits */\n        int     ResvMax;     /* in bits */\n\n        int     in_buffer_nsamples;\n        sample_t *in_buffer_0;\n        sample_t *in_buffer_1;\n\n#ifndef  MFSIZE\n# define MFSIZE  ( 3*1152 + ENCDELAY - MDCTDELAY )\n#endif\n        sample_t mfbuf[2][MFSIZE];\n\n        int     mf_samples_to_encode;\n        int     mf_size;\n\n    } EncStateVar_t;\n\n\n    typedef struct {\n        /* simple statistics */\n        int     bitrate_channelmode_hist[16][4 + 1];\n        int     bitrate_blocktype_hist[16][4 + 1 + 1]; /*norm/start/short/stop/mixed(short)/sum */\n\n        int     bitrate_index;\n        int     frame_number; /* number of frames encoded             */\n        int     padding;     /* padding for the current frame? */\n        int     mode_ext;\n        int     encoder_delay;\n        int     encoder_padding; /* number of samples of padding appended to input */\n    } EncResult_t;\n\n\n    /* variables used by quantize.c */\n    typedef struct {\n        /* variables for nspsytune */\n        FLOAT   longfact[SBMAX_l];\n        FLOAT   shortfact[SBMAX_s];\n        FLOAT   masking_lower;\n        FLOAT   mask_adjust; /* the dbQ stuff */\n        FLOAT   mask_adjust_short; /* the dbQ stuff */\n        int     OldValue[2];\n        int     CurrentStep[2];\n        int     pseudohalf[SFBMAX];\n        int     sfb21_extra; /* will be set in lame_init_params */\n        int     substep_shaping; /* 0 = no substep\n                                    1 = use substep shaping at last step(VBR only)\n                                    (not implemented yet)\n                                    2 = use substep inside loop\n                                    3 = use substep inside loop and last step\n                                  */\n\n\n        char    bv_scf[576];\n    } QntStateVar_t;\n\n\n    typedef struct {\n        replaygain_t *rgdata;\n        /* ReplayGain */\n    } RpgStateVar_t;\n\n\n    typedef struct {\n        FLOAT   noclipScale; /* user-specified scale factor required for preventing clipping */\n        sample_t PeakSample;\n        int     RadioGain;\n        int     noclipGainChange; /* gain change required for preventing clipping */\n    } RpgResult_t;\n\n\n    typedef struct {\n        int     version;     /* 0=MPEG-2/2.5  1=MPEG-1               */\n        int     samplerate_index;\n        int     sideinfo_len;\n\n        int     noise_shaping; /* 0 = none\n                                  1 = ISO AAC model\n                                  2 = allow scalefac_select=1\n                                */\n\n        int     subblock_gain; /*  0 = no, 1 = yes */\n        int     use_best_huffman; /* 0 = no.  1=outside loop  2=inside loop(slow) */\n        int     noise_shaping_amp; /*  0 = ISO model: amplify all distorted bands\n                                      1 = amplify within 50% of max (on db scale)\n                                      2 = amplify only most distorted band\n                                      3 = method 1 and refine with method 2\n                                    */\n\n        int     noise_shaping_stop; /* 0 = stop at over=0, all scalefacs amplified or\n                                       a scalefac has reached max value\n                                       1 = stop when all scalefacs amplified or\n                                       a scalefac has reached max value\n                                       2 = stop when all scalefacs amplified\n                                     */\n\n\n        int     full_outer_loop; /* 0 = stop early after 0 distortion found. 1 = full search */\n\n        int     lowpassfreq;\n        int     highpassfreq;\n        int     samplerate_in; /* input_samp_rate in Hz. default=44.1 kHz     */\n        int     samplerate_out; /* output_samp_rate. */\n        int     channels_in; /* number of channels in the input data stream (PCM or decoded PCM) */\n        int     channels_out; /* number of channels in the output data stream (not used for decoding) */\n        int     mode_gr;     /* granules per frame */\n        int     force_ms;    /* force M/S mode.  requires mode=1            */\n\n        int     quant_comp;\n        int     quant_comp_short;\n\n        int     use_temporal_masking_effect;\n        int     use_safe_joint_stereo;\n\n        int     preset;\n\n        vbr_mode vbr;\n        int     vbr_avg_bitrate_kbps;\n        int     vbr_min_bitrate_index; /* min bitrate index */\n        int     vbr_max_bitrate_index; /* max bitrate index */\n        int     avg_bitrate;\n        int     enforce_min_bitrate; /* strictly enforce VBR_min_bitrate normaly, it will be violated for analog silence */\n\n        int     findReplayGain; /* find the RG value? default=0       */\n        int     findPeakSample;\n        int     decode_on_the_fly; /* decode on the fly? default=0                */\n        int     analysis;\n        int     disable_reservoir;\n        int     buffer_constraint;  /* enforce ISO spec as much as possible   */\n        int     free_format;\n        int     write_lame_tag; /* add Xing VBR tag?                           */\n\n        int     error_protection; /* use 2 bytes per frame for a CRC checksum. default=0 */\n        int     copyright;   /* mark as copyright. default=0           */\n        int     original;    /* mark as original. default=1            */\n        int     extension;   /* the MP3 'private extension' bit. Meaningless */\n        int     emphasis;    /* Input PCM is emphased PCM (for\n                                instance from one of the rarely\n                                emphased CDs), it is STRONGLY not\n                                recommended to use this, because\n                                psycho does not take it into account,\n                                and last but not least many decoders\n                                don't care about these bits          */\n\n\n        MPEG_mode mode;\n        short_block_t short_blocks;\n\n        float   interChRatio;\n        float   msfix;       /* Naoki's adjustment of Mid/Side maskings */\n        float   ATH_offset_db;/* add to ATH this many db            */\n        float   ATH_offset_factor;/* change ATH by this factor, derived from ATH_offset_db */\n        float   ATHcurve;    /* change ATH formula 4 shape           */\n        int     ATHtype;\n        int     ATHonly;     /* only use ATH                         */\n        int     ATHshort;    /* only use ATH for short blocks        */\n        int     noATH;       /* disable ATH                          */\n        \n        float   ATHfixpoint;\n\n        float   adjust_alto_db;\n        float   adjust_bass_db;\n        float   adjust_treble_db;\n        float   adjust_sfb21_db;\n\n        float   compression_ratio; /* sizeof(wav file)/sizeof(mp3 file)          */\n\n        /* lowpass and highpass filter control */\n        FLOAT   lowpass1, lowpass2; /* normalized frequency bounds of passband */\n        FLOAT   highpass1, highpass2; /* normalized frequency bounds of passband */\n\n        /* scale input by this amount before encoding at least not used for MP3 decoding */\n        FLOAT   pcm_transform[2][2];\n\n        FLOAT   minval;\n    } SessionConfig_t;\n\n\n    struct lame_internal_flags {\n\n  /********************************************************************\n   * internal variables NOT set by calling program, and should not be *\n   * modified by the calling program                                  *\n   ********************************************************************/\n\n        /*\n         * Some remarks to the Class_ID field:\n         * The Class ID is an Identifier for a pointer to this struct.\n         * It is very unlikely that a pointer to lame_global_flags has the same 32 bits\n         * in it's structure (large and other special properties, for instance prime).\n         *\n         * To test that the structure is right and initialized, use:\n         *     if ( gfc -> Class_ID == LAME_ID ) ...\n         * Other remark:\n         *     If you set a flag to 0 for uninit data and 1 for init data, the right test\n         *     should be \"if (flag == 1)\" and NOT \"if (flag)\". Unintended modification\n         *     of this element will be otherwise misinterpreted as an init.\n         */\n#  define  LAME_ID   0xFFF88E3B\n        unsigned long class_id;\n\n        int     lame_encode_frame_init;\n        int     iteration_init_init;\n        int     fill_buffer_resample_init;\n\n        SessionConfig_t cfg;\n\n        /* variables used by lame.c */\n        Bit_stream_struc bs;\n        III_side_info_t l3_side;\n\n        scalefac_struct scalefac_band;\n\n        PsyStateVar_t sv_psy; /* DATA FROM PSYMODEL.C */\n        PsyResult_t ov_psy;\n        EncStateVar_t sv_enc; /* DATA FROM ENCODER.C */\n        EncResult_t ov_enc;\n        QntStateVar_t sv_qnt; /* DATA FROM QUANTIZE.C */\n\n        RpgStateVar_t sv_rpg;\n        RpgResult_t ov_rpg;\n\n        /* optional ID3 tags, used in id3tag.c  */\n        struct id3tag_spec tag_spec;\n        uint16_t nMusicCRC;\n\n        uint16_t _unused;\n\n        /* CPU features */\n        struct {\n            unsigned int MMX:1; /* Pentium MMX, Pentium II...IV, K6, K6-2,\n                                   K6-III, Athlon */\n            unsigned int AMD_3DNow:1; /* K6-2, K6-III, Athlon      */\n            unsigned int SSE:1; /* Pentium III, Pentium 4    */\n            unsigned int SSE2:1; /* Pentium 4, K8             */\n            unsigned int _unused:28;\n        } CPU_features;\n\n\n        VBR_seek_info_t VBR_seek_table; /* used for Xing VBR header */\n\n        ATH_t  *ATH;         /* all ATH related stuff */\n\n        PsyConst_t *cd_psy;\n\n        /* used by the frame analyzer */\n        plotting_data *pinfo;\n        hip_t hip;\n\n        iteration_loop_t iteration_loop;\n\n        /* functions to replace with CPU feature optimized versions in takehiro.c */\n        int     (*choose_table) (const int *ix, const int *const end, int *const s);\n        void    (*fft_fht) (FLOAT *, int);\n        void    (*init_xrpow_core) (gr_info * const cod_info, FLOAT xrpow[576], int upper,\n                                    FLOAT * sum);\n\n        lame_report_function report_msg;\n        lame_report_function report_dbg;\n        lame_report_function report_err;\n    };\n\n#ifndef lame_internal_flags_defined\n#define lame_internal_flags_defined\n    typedef struct lame_internal_flags lame_internal_flags;\n#endif\n\n\n/***********************************************************************\n*\n*  Global Function Prototype Declarations\n*\n***********************************************************************/\n    void    freegfc(lame_internal_flags * const gfc);\n    void    free_id3tag(lame_internal_flags * const gfc);\n    extern int BitrateIndex(int, int, int);\n    extern int FindNearestBitrate(int, int, int);\n    extern int map2MP3Frequency(int freq);\n    extern int SmpFrqIndex(int, int *const);\n    extern int nearestBitrateFullIndex(uint16_t brate);\n    extern FLOAT ATHformula(SessionConfig_t const *cfg, FLOAT freq);\n    extern FLOAT freq2bark(FLOAT freq);\n    void    disable_FPE(void);\n\n/* log/log10 approximations */\n    extern void init_log_table(void);\n    extern float fast_log2(float x);\n\n    int     isResamplingNecessary(SessionConfig_t const* cfg);\n\n    void    fill_buffer(lame_internal_flags * gfc,\n                        sample_t *const mfbuf[2],\n                        sample_t const *const in_buffer[2], int nsamples, int *n_in, int *n_out);\n\n/* same as lame_decode1 (look in lame.h), but returns\n   unclipped raw floating-point samples. It is declared\n   here, not in lame.h, because it returns LAME's\n   internal type sample_t. No more than 1152 samples\n   per channel are allowed. */\n    int     hip_decode1_unclipped(hip_t hip, unsigned char *mp3buf,\n                                   size_t len, sample_t pcm_l[], sample_t pcm_r[]);\n\n\n    extern int has_MMX(void);\n    extern int has_3DNow(void);\n    extern int has_SSE(void);\n    extern int has_SSE2(void);\n\n\n\n/***********************************************************************\n*\n*  Macros about Message Printing and Exit\n*\n***********************************************************************/\n\n    extern void lame_report_def(const char* format, va_list args);\n    extern void lame_report_fnc(lame_report_function print_f, const char *, ...);\n    extern void lame_errorf(const lame_internal_flags * gfc, const char *, ...);\n    extern void lame_debugf(const lame_internal_flags * gfc, const char *, ...);\n    extern void lame_msgf(const lame_internal_flags * gfc, const char *, ...);\n#define DEBUGF  lame_debugf\n#define ERRORF  lame_errorf\n#define MSGF    lame_msgf\n\n    int     is_lame_internal_flags_valid(const lame_internal_flags * gfp);\n    \n    extern void hip_set_pinfo(hip_t hip, plotting_data* pinfo);\n\n#ifdef __cplusplus\n}\n#endif\n#endif                       /* LAME_UTIL_H */\n"
  },
  {
    "path": "app/jni/libmp3lame/vbrquantize.c",
    "content": "/*\n *\tMP3 quantization\n *\n *\tCopyright (c) 1999-2000 Mark Taylor\n *\tCopyright (c) 2000-2012 Robert Hegemann\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/* $Id: vbrquantize.c,v 1.141.2.1 2012/02/07 13:40:37 robert Exp $ */\n\n#ifdef HAVE_CONFIG_H\n#  include <config.h>\n#endif\n\n\n#include <string.h>\n#include <stdlib.h>\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"vbrquantize.h\"\n#include \"quantize_pvt.h\"\n\n\n\n\nstruct algo_s;\ntypedef struct algo_s algo_t;\n\ntypedef void (*alloc_sf_f) (const algo_t *, const int *, const int *, int);\ntypedef uint8_t (*find_sf_f) (const FLOAT *, const FLOAT *, FLOAT, unsigned int, uint8_t);\n\nstruct algo_s {\n    alloc_sf_f alloc;\n    find_sf_f  find;\n    const FLOAT *xr34orig;\n    lame_internal_flags *gfc;\n    gr_info *cod_info;\n    int     mingain_l;\n    int     mingain_s[3];\n};\n\n\n\n/*  Remarks on optimizing compilers:\n *\n *  the MSVC compiler may get into aliasing problems when accessing\n *  memory through the fi_union. declaring it volatile does the trick here\n *\n *  the calc_sfb_noise_* functions are not inlined because the intel compiler\n *  optimized executeables won't work as expected anymore\n */\n\n#ifdef _MSC_VER\n#  if _MSC_VER < 1400\n#  define VOLATILE volatile\n#  else\n#  define VOLATILE\n#  endif\n#else\n#  define VOLATILE\n#endif\n\ntypedef VOLATILE union {\n    float   f;\n    int     i;\n} fi_union;\n\n\n\n#ifdef TAKEHIRO_IEEE754_HACK\n#define DOUBLEX double\n#else\n#define DOUBLEX FLOAT\n#endif\n \n#define MAGIC_FLOAT_def (65536*(128))\n#define MAGIC_INT_def    0x4b000000\n\n#ifdef TAKEHIRO_IEEE754_HACK\n#else\n/*********************************************************************\n * XRPOW_FTOI is a macro to convert floats to ints.\n * if XRPOW_FTOI(x) = nearest_int(x), then QUANTFAC(x)=adj43asm[x]\n *                                         ROUNDFAC= -0.0946\n *\n * if XRPOW_FTOI(x) = floor(x), then QUANTFAC(x)=asj43[x]\n *                                   ROUNDFAC=0.4054\n *********************************************************************/\n#  define QUANTFAC(rx)  adj43[rx]\n#  define ROUNDFAC_def 0.4054f\n#  define XRPOW_FTOI(src,dest) ((dest) = (int)(src))\n#endif\n\nstatic int const MAGIC_INT = MAGIC_INT_def;\n#ifndef TAKEHIRO_IEEE754_HACK\nstatic DOUBLEX const ROUNDFAC = ROUNDFAC_def;\n#endif\nstatic DOUBLEX const MAGIC_FLOAT = MAGIC_FLOAT_def;\n\n\ninline static  float\nvec_max_c(const float * xr34, unsigned int bw)\n{\n    float   xfsf = 0;\n    unsigned int i = bw >> 2u;\n    unsigned int const remaining = (bw & 0x03u);\n\n    while (i-- > 0) {\n        if (xfsf < xr34[0]) {\n            xfsf = xr34[0];\n        }\n        if (xfsf < xr34[1]) {\n            xfsf = xr34[1];\n        }\n        if (xfsf < xr34[2]) {\n            xfsf = xr34[2];\n        }\n        if (xfsf < xr34[3]) {\n            xfsf = xr34[3];\n        }\n        xr34 += 4;\n    }\n    switch( remaining ) {\n    case 3: if (xfsf < xr34[2]) xfsf = xr34[2];\n    case 2: if (xfsf < xr34[1]) xfsf = xr34[1];\n    case 1: if (xfsf < xr34[0]) xfsf = xr34[0];\n    default: break;\n    }\n    return xfsf;\n}\n\n\ninline static  uint8_t\nfind_lowest_scalefac(const FLOAT xr34)\n{\n    uint8_t sf_ok = 255;\n    uint8_t sf = 128, delsf = 64;\n    uint8_t i;\n    FLOAT const ixmax_val = IXMAX_VAL;\n    for (i = 0; i < 8; ++i) {\n        FLOAT const xfsf = ipow20[sf] * xr34;\n        if (xfsf <= ixmax_val) {\n            sf_ok = sf;\n            sf -= delsf;\n        }\n        else {\n            sf += delsf;\n        }\n        delsf >>= 1;\n    }\n    return sf_ok;\n}\n\n\ninline static void\nk_34_4(DOUBLEX x[4], int l3[4])\n{\n#ifdef TAKEHIRO_IEEE754_HACK\n    fi_union fi[4];\n\n    assert(x[0] <= IXMAX_VAL && x[1] <= IXMAX_VAL && x[2] <= IXMAX_VAL && x[3] <= IXMAX_VAL);\n    x[0] += MAGIC_FLOAT;\n    fi[0].f = x[0];\n    x[1] += MAGIC_FLOAT;\n    fi[1].f = x[1];\n    x[2] += MAGIC_FLOAT;\n    fi[2].f = x[2];\n    x[3] += MAGIC_FLOAT;\n    fi[3].f = x[3];\n    fi[0].f = x[0] + adj43asm[fi[0].i - MAGIC_INT];\n    fi[1].f = x[1] + adj43asm[fi[1].i - MAGIC_INT];\n    fi[2].f = x[2] + adj43asm[fi[2].i - MAGIC_INT];\n    fi[3].f = x[3] + adj43asm[fi[3].i - MAGIC_INT];\n    l3[0] = fi[0].i - MAGIC_INT;\n    l3[1] = fi[1].i - MAGIC_INT;\n    l3[2] = fi[2].i - MAGIC_INT;\n    l3[3] = fi[3].i - MAGIC_INT;\n#else\n    assert(x[0] <= IXMAX_VAL && x[1] <= IXMAX_VAL && x[2] <= IXMAX_VAL && x[3] <= IXMAX_VAL);\n    XRPOW_FTOI(x[0], l3[0]);\n    XRPOW_FTOI(x[1], l3[1]);\n    XRPOW_FTOI(x[2], l3[2]);\n    XRPOW_FTOI(x[3], l3[3]);\n    x[0] += QUANTFAC(l3[0]);\n    x[1] += QUANTFAC(l3[1]);\n    x[2] += QUANTFAC(l3[2]);\n    x[3] += QUANTFAC(l3[3]);\n    XRPOW_FTOI(x[0], l3[0]);\n    XRPOW_FTOI(x[1], l3[1]);\n    XRPOW_FTOI(x[2], l3[2]);\n    XRPOW_FTOI(x[3], l3[3]);\n#endif\n}\n\n\n\n\n\n/*  do call the calc_sfb_noise_* functions only with sf values\n *  for which holds: sfpow34*xr34 <= IXMAX_VAL\n */\n\nstatic  FLOAT\ncalc_sfb_noise_x34(const FLOAT * xr, const FLOAT * xr34, unsigned int bw, uint8_t sf)\n{\n    DOUBLEX x[4];\n    int     l3[4];\n    const FLOAT sfpow = pow20[sf + Q_MAX2]; /*pow(2.0,sf/4.0); */\n    const FLOAT sfpow34 = ipow20[sf]; /*pow(sfpow,-3.0/4.0); */\n\n    FLOAT   xfsf = 0;\n    unsigned int i = bw >> 2u;\n    unsigned int const remaining = (bw & 0x03u);\n\n    while (i-- > 0) {\n        x[0] = sfpow34 * xr34[0];\n        x[1] = sfpow34 * xr34[1];\n        x[2] = sfpow34 * xr34[2];\n        x[3] = sfpow34 * xr34[3];\n\n        k_34_4(x, l3);\n\n        x[0] = fabsf(xr[0]) - sfpow * pow43[l3[0]];\n        x[1] = fabsf(xr[1]) - sfpow * pow43[l3[1]];\n        x[2] = fabsf(xr[2]) - sfpow * pow43[l3[2]];\n        x[3] = fabsf(xr[3]) - sfpow * pow43[l3[3]];\n        xfsf += (x[0] * x[0] + x[1] * x[1]) + (x[2] * x[2] + x[3] * x[3]);\n\n        xr += 4;\n        xr34 += 4;\n    }\n    if (remaining) {\n        x[0] = x[1] = x[2] = x[3] = 0;\n        switch( remaining ) {\n        case 3: x[2] = sfpow34 * xr34[2];\n        case 2: x[1] = sfpow34 * xr34[1];\n        case 1: x[0] = sfpow34 * xr34[0];\n        }\n\n        k_34_4(x, l3);\n        x[0] = x[1] = x[2] = x[3] = 0;\n\n        switch( remaining ) {\n        case 3: x[2] = fabsf(xr[2]) - sfpow * pow43[l3[2]];\n        case 2: x[1] = fabsf(xr[1]) - sfpow * pow43[l3[1]];\n        case 1: x[0] = fabsf(xr[0]) - sfpow * pow43[l3[0]];\n        }\n        xfsf += (x[0] * x[0] + x[1] * x[1]) + (x[2] * x[2] + x[3] * x[3]);\n    }\n    return xfsf;\n}\n\n\n\nstruct calc_noise_cache {\n    int     valid;\n    FLOAT   value;\n};\n\ntypedef struct calc_noise_cache calc_noise_cache_t;\n\n\nstatic  uint8_t\ntri_calc_sfb_noise_x34(const FLOAT * xr, const FLOAT * xr34, FLOAT l3_xmin, unsigned int bw,\n                       uint8_t sf, calc_noise_cache_t * did_it)\n{\n    if (did_it[sf].valid == 0) {\n        did_it[sf].valid = 1;\n        did_it[sf].value = calc_sfb_noise_x34(xr, xr34, bw, sf);\n    }\n    if (l3_xmin < did_it[sf].value) {\n        return 1;\n    }\n    if (sf < 255) {\n        uint8_t const sf_x = sf + 1;\n        if (did_it[sf_x].valid == 0) {\n            did_it[sf_x].valid = 1;\n            did_it[sf_x].value = calc_sfb_noise_x34(xr, xr34, bw, sf_x);\n        }\n        if (l3_xmin < did_it[sf_x].value) {\n            return 1;\n        }\n    }\n    if (sf > 0) {\n        uint8_t const sf_x = sf - 1;\n        if (did_it[sf_x].valid == 0) {\n            did_it[sf_x].valid = 1;\n            did_it[sf_x].value = calc_sfb_noise_x34(xr, xr34, bw, sf_x);\n        }\n        if (l3_xmin < did_it[sf_x].value) {\n            return 1;\n        }\n    }\n    return 0;\n}\n\n\n/**\n *  Robert Hegemann 2001-05-01\n *  calculates quantization step size determined by allowed masking\n */\nstatic int\ncalc_scalefac(FLOAT l3_xmin, int bw)\n{\n    FLOAT const c = 5.799142446; /* 10 * 10^(2/3) * log10(4/3) */\n    return 210 + (int) (c * log10f(l3_xmin / bw) - .5f);\n}\n\nstatic uint8_t\nguess_scalefac_x34(const FLOAT * xr, const FLOAT * xr34, FLOAT l3_xmin, unsigned int bw, uint8_t sf_min)\n{\n    int const guess = calc_scalefac(l3_xmin, bw);\n    if (guess < sf_min) return sf_min;\n    if (guess >= 255) return 255;\n    (void) xr;\n    (void) xr34;\n    return guess;\n}\n\n\n/* the find_scalefac* routines calculate\n * a quantization step size which would\n * introduce as much noise as is allowed.\n * The larger the step size the more\n * quantization noise we'll get. The\n * scalefactors are there to lower the\n * global step size, allowing limited\n * differences in quantization step sizes\n * per band (shaping the noise).\n */\n\nstatic  uint8_t\nfind_scalefac_x34(const FLOAT * xr, const FLOAT * xr34, FLOAT l3_xmin, unsigned int bw,\n                  uint8_t sf_min)\n{\n    calc_noise_cache_t did_it[256];\n    uint8_t sf = 128, sf_ok = 255, delsf = 128, seen_good_one = 0, i;\n    memset(did_it, 0, sizeof(did_it));\n    for (i = 0; i < 8; ++i) {\n        delsf >>= 1;\n        if (sf <= sf_min) {\n            sf += delsf;\n        }\n        else {\n            uint8_t const bad = tri_calc_sfb_noise_x34(xr, xr34, l3_xmin, bw, sf, did_it);\n            if (bad) {  /* distortion.  try a smaller scalefactor */\n                sf -= delsf;\n            }\n            else {\n                sf_ok = sf;\n                sf += delsf;\n                seen_good_one = 1;\n            }\n        }\n    }\n    /*  returning a scalefac without distortion, if possible\n     */\n    if (seen_good_one > 0) {\n        sf = sf_ok;\n    }\n    if (sf <= sf_min) {\n        sf = sf_min;\n    }\n    return sf;\n}\n\n\n\n/***********************************************************************\n *\n *      calc_short_block_vbr_sf()\n *      calc_long_block_vbr_sf()\n *\n *  Mark Taylor 2000-??-??\n *  Robert Hegemann 2000-10-25 made functions of it\n *\n ***********************************************************************/\n\n/* a variation for vbr-mtrh */\nstatic int\nblock_sf(algo_t * that, const FLOAT l3_xmin[SFBMAX], int vbrsf[SFBMAX], int vbrsfmin[SFBMAX])\n{\n    FLOAT   max_xr34;\n    const FLOAT *const xr = &that->cod_info->xr[0];\n    const FLOAT *const xr34_orig = &that->xr34orig[0];\n    const int *const width = &that->cod_info->width[0];\n    const char *const energy_above_cutoff = &that->cod_info->energy_above_cutoff[0];\n    unsigned int const max_nonzero_coeff = (unsigned int) that->cod_info->max_nonzero_coeff;\n    uint8_t maxsf = 0;\n    int     sfb = 0, m_o = -1;\n    unsigned int j = 0, i = 0;\n    int const psymax = that->cod_info->psymax;\n\n    assert(that->cod_info->max_nonzero_coeff >= 0);\n\n    that->mingain_l = 0;\n    that->mingain_s[0] = 0;\n    that->mingain_s[1] = 0;\n    that->mingain_s[2] = 0;\n    while (j <= max_nonzero_coeff) {\n        unsigned int const w = (unsigned int) width[sfb];\n        unsigned int const m = (unsigned int) (max_nonzero_coeff - j + 1);\n        unsigned int l = w;\n        uint8_t m1, m2;\n        if (l > m) {\n            l = m;\n        }\n        max_xr34 = vec_max_c(&xr34_orig[j], l);\n\n        m1 = find_lowest_scalefac(max_xr34);\n        vbrsfmin[sfb] = m1;\n        if (that->mingain_l < m1) {\n            that->mingain_l = m1;\n        }\n        if (that->mingain_s[i] < m1) {\n            that->mingain_s[i] = m1;\n        }\n        if (++i > 2) {\n            i = 0;\n        }\n        if (sfb < psymax && w > 2) { /* mpeg2.5 at 8 kHz doesn't use all scalefactors, unused have width 2 */\n            if (energy_above_cutoff[sfb]) {\n                m2 = that->find(&xr[j], &xr34_orig[j], l3_xmin[sfb], l, m1);\n#if 0\n                if (0) {\n                    /** Robert Hegemann 2007-09-29:\n                     *  It seems here is some more potential for speed improvements.\n                     *  Current find method does 11-18 quantization calculations.\n                     *  Using a \"good guess\" may help to reduce this amount.\n                     */\n                    uint8_t guess = calc_scalefac(l3_xmin[sfb], l);\n                    DEBUGF(that->gfc, \"sfb=%3d guess=%3d found=%3d diff=%3d\\n\", sfb, guess, m2,\n                           m2 - guess);\n                }\n#endif\n                if (maxsf < m2) {\n                    maxsf = m2;\n                }\n                if (m_o < m2 && m2 < 255) {\n                    m_o = m2;\n                }\n            }\n            else {\n                m2 = 255;\n                maxsf = 255;\n            }\n        }\n        else {\n            if (maxsf < m1) {\n                maxsf = m1;\n            }\n            m2 = maxsf;\n        }\n        vbrsf[sfb] = m2;\n        ++sfb;\n        j += w;        \n    }\n    for (; sfb < SFBMAX; ++sfb) {\n        vbrsf[sfb] = maxsf;\n        vbrsfmin[sfb] = 0;\n    }\n    if (m_o > -1) {\n        maxsf = m_o;\n        for (sfb = 0; sfb < SFBMAX; ++sfb) {\n            if (vbrsf[sfb] == 255) {\n                vbrsf[sfb] = m_o;\n            }\n        }\n    }\n    return maxsf;\n}\n\n\n\n/***********************************************************************\n *\n *  quantize xr34 based on scalefactors\n *\n *  block_xr34\n *\n *  Mark Taylor 2000-??-??\n *  Robert Hegemann 2000-10-20 made functions of them\n *\n ***********************************************************************/\n\nstatic void\nquantize_x34(const algo_t * that)\n{\n    DOUBLEX x[4];\n    const FLOAT *xr34_orig = that->xr34orig;\n    gr_info *const cod_info = that->cod_info;\n    int const ifqstep = (cod_info->scalefac_scale == 0) ? 2 : 4;\n    int    *l3 = cod_info->l3_enc;\n    unsigned int j = 0, sfb = 0;\n    unsigned int const max_nonzero_coeff = (unsigned int) cod_info->max_nonzero_coeff;\n\n    assert(cod_info->max_nonzero_coeff >= 0);\n    assert(cod_info->max_nonzero_coeff < 576);\n\n    while (j <= max_nonzero_coeff) {\n        int const s =\n            (cod_info->scalefac[sfb] + (cod_info->preflag ? pretab[sfb] : 0)) * ifqstep\n            + cod_info->subblock_gain[cod_info->window[sfb]] * 8;\n        uint8_t const sfac = (uint8_t) (cod_info->global_gain - s);\n        FLOAT const sfpow34 = ipow20[sfac];\n        unsigned int const w = (unsigned int) cod_info->width[sfb];\n        unsigned int const m = (unsigned int) (max_nonzero_coeff - j + 1);\n        unsigned int i, remaining;\n\n        assert((cod_info->global_gain - s) >= 0);\n        assert(cod_info->width[sfb] >= 0);\n        j += w;\n        ++sfb;\n        \n        i = (w <= m) ? w : m;\n        remaining = (i & 0x03u);\n        i >>= 2u;\n\n        while (i-- > 0) {\n            x[0] = sfpow34 * xr34_orig[0];\n            x[1] = sfpow34 * xr34_orig[1];\n            x[2] = sfpow34 * xr34_orig[2];\n            x[3] = sfpow34 * xr34_orig[3];\n\n            k_34_4(x, l3);\n\n            l3 += 4;\n            xr34_orig += 4;\n        }\n        if (remaining) {\n            int tmp_l3[4];\n            x[0] = x[1] = x[2] = x[3] = 0;\n            switch( remaining ) {\n            case 3: x[2] = sfpow34 * xr34_orig[2];\n            case 2: x[1] = sfpow34 * xr34_orig[1];\n            case 1: x[0] = sfpow34 * xr34_orig[0];\n            }\n\n            k_34_4(x, tmp_l3);\n\n            switch( remaining ) {\n            case 3: l3[2] = tmp_l3[2];\n            case 2: l3[1] = tmp_l3[1];\n            case 1: l3[0] = tmp_l3[0];\n            }\n\n            l3 += remaining;\n            xr34_orig += remaining;\n        }\n    }\n}\n\n\n\nstatic const uint8_t max_range_short[SBMAX_s * 3] = {\n    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,\n    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n    0, 0, 0\n};\n\nstatic const uint8_t max_range_long[SBMAX_l] = {\n    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 0\n};\n\nstatic const uint8_t max_range_long_lsf_pretab[SBMAX_l] = {\n    7, 7, 7, 7, 7, 7, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0\n};\n\n\n\n/*\n    sfb=0..5  scalefac < 16\n    sfb>5     scalefac < 8\n\n    ifqstep = ( cod_info->scalefac_scale == 0 ) ? 2 : 4;\n    ol_sf =  (cod_info->global_gain-210.0);\n    ol_sf -= 8*cod_info->subblock_gain[i];\n    ol_sf -= ifqstep*scalefac[gr][ch].s[sfb][i];\n*/\n\nstatic void\nset_subblock_gain(gr_info * cod_info, const int mingain_s[3], int sf[])\n{\n    const int maxrange1 = 15, maxrange2 = 7;\n    const int ifqstepShift = (cod_info->scalefac_scale == 0) ? 1 : 2;\n    int    *const sbg = cod_info->subblock_gain;\n    unsigned int const psymax = (unsigned int) cod_info->psymax;\n    unsigned int psydiv = 18;\n    int     sbg0, sbg1, sbg2;\n    unsigned int sfb, i;\n    int     min_sbg = 7;\n\n    if (psydiv > psymax) {\n        psydiv = psymax;\n    }\n    for (i = 0; i < 3; ++i) {\n        int     maxsf1 = 0, maxsf2 = 0, minsf = 1000;\n        /* see if we should use subblock gain */\n        for (sfb = i; sfb < psydiv; sfb += 3) { /* part 1 */\n            int const v = -sf[sfb];\n            if (maxsf1 < v) {\n                maxsf1 = v;\n            }\n            if (minsf > v) {\n                minsf = v;\n            }\n        }\n        for (; sfb < SFBMAX; sfb += 3) { /* part 2 */\n            int const v = -sf[sfb];\n            if (maxsf2 < v) {\n                maxsf2 = v;\n            }\n            if (minsf > v) {\n                minsf = v;\n            }\n        }\n\n        /* boost subblock gain as little as possible so we can\n         * reach maxsf1 with scalefactors\n         * 8*sbg >= maxsf1\n         */\n        {\n            int const m1 = maxsf1 - (maxrange1 << ifqstepShift);\n            int const m2 = maxsf2 - (maxrange2 << ifqstepShift);\n\n            maxsf1 = Max(m1, m2);\n        }\n        if (minsf > 0) {\n            sbg[i] = minsf >> 3;\n        }\n        else {\n            sbg[i] = 0;\n        }\n        if (maxsf1 > 0) {\n            int const m1 = sbg[i];\n            int const m2 = (maxsf1 + 7) >> 3;\n            sbg[i] = Max(m1, m2);\n        }\n        if (sbg[i] > 0 && mingain_s[i] > (cod_info->global_gain - sbg[i] * 8)) {\n            sbg[i] = (cod_info->global_gain - mingain_s[i]) >> 3;\n        }\n        if (sbg[i] > 7) {\n            sbg[i] = 7;\n        }\n        if (min_sbg > sbg[i]) {\n            min_sbg = sbg[i];\n        }\n    }\n    sbg0 = sbg[0] * 8;\n    sbg1 = sbg[1] * 8;\n    sbg2 = sbg[2] * 8;\n    for (sfb = 0; sfb < SFBMAX; sfb += 3) {\n        sf[sfb + 0] += sbg0;\n        sf[sfb + 1] += sbg1;\n        sf[sfb + 2] += sbg2;\n    }\n    if (min_sbg > 0) {\n        for (i = 0; i < 3; ++i) {\n            sbg[i] -= min_sbg;\n        }\n        cod_info->global_gain -= min_sbg * 8;\n    }\n}\n\n\n\n/*\n\t  ifqstep = ( cod_info->scalefac_scale == 0 ) ? 2 : 4;\n\t  ol_sf =  (cod_info->global_gain-210.0);\n\t  ol_sf -= ifqstep*scalefac[gr][ch].l[sfb];\n\t  if (cod_info->preflag && sfb>=11)\n\t  ol_sf -= ifqstep*pretab[sfb];\n*/\nstatic void\nset_scalefacs(gr_info * cod_info, const int *vbrsfmin, int sf[], const uint8_t * max_range)\n{\n    const int ifqstep = (cod_info->scalefac_scale == 0) ? 2 : 4;\n    const int ifqstepShift = (cod_info->scalefac_scale == 0) ? 1 : 2;\n    int    *const scalefac = cod_info->scalefac;\n    int const sfbmax = cod_info->sfbmax;\n    int     sfb;\n    int const *const sbg = cod_info->subblock_gain;\n    int const *const window = cod_info->window;\n    int const preflag = cod_info->preflag;\n\n    if (preflag) {\n        for (sfb = 11; sfb < sfbmax; ++sfb) {\n            sf[sfb] += pretab[sfb] * ifqstep;\n        }\n    }\n    for (sfb = 0; sfb < sfbmax; ++sfb) {\n        int const gain = cod_info->global_gain - (sbg[window[sfb]] * 8)\n            - ((preflag ? pretab[sfb] : 0) * ifqstep);\n\n        if (sf[sfb] < 0) {\n            int const m = gain - vbrsfmin[sfb];\n            /* ifqstep*scalefac >= -sf[sfb], so round UP */\n            scalefac[sfb] = (ifqstep - 1 - sf[sfb]) >> ifqstepShift;\n\n            if (scalefac[sfb] > max_range[sfb]) {\n                scalefac[sfb] = max_range[sfb];\n            }\n            if (scalefac[sfb] > 0 && (scalefac[sfb] << ifqstepShift) > m) {\n                scalefac[sfb] = m >> ifqstepShift;\n            }\n        }\n        else {\n            scalefac[sfb] = 0;\n        }\n    }\n    for (; sfb < SFBMAX; ++sfb) {\n        scalefac[sfb] = 0; /* sfb21 */\n    }\n}\n\n\n#ifndef NDEBUG\nstatic int\ncheckScalefactor(const gr_info * cod_info, const int vbrsfmin[SFBMAX])\n{\n    int const ifqstep = cod_info->scalefac_scale == 0 ? 2 : 4;\n    int     sfb;\n    for (sfb = 0; sfb < cod_info->psymax; ++sfb) {\n        const int s =\n            ((cod_info->scalefac[sfb] +\n              (cod_info->preflag ? pretab[sfb] : 0)) * ifqstep) +\n            cod_info->subblock_gain[cod_info->window[sfb]] * 8;\n\n        if ((cod_info->global_gain - s) < vbrsfmin[sfb]) {\n            /*\n               fprintf( stdout, \"sf %d\\n\", sfb );\n               fprintf( stdout, \"min %d\\n\", vbrsfmin[sfb] );\n               fprintf( stdout, \"ggain %d\\n\", cod_info->global_gain );\n               fprintf( stdout, \"scalefac %d\\n\", cod_info->scalefac[sfb] );\n               fprintf( stdout, \"pretab %d\\n\", (cod_info->preflag ? pretab[sfb] : 0) );\n               fprintf( stdout, \"scale %d\\n\", (cod_info->scalefac_scale + 1) );\n               fprintf( stdout, \"subgain %d\\n\", cod_info->subblock_gain[cod_info->window[sfb]] * 8 );\n               fflush( stdout );\n               exit(-1);\n             */\n            return 0;\n        }\n    }\n    return 1;\n}\n#endif\n\n\n/******************************************************************\n *\n *  short block scalefacs\n *\n ******************************************************************/\n\nstatic void\nshort_block_constrain(const algo_t * that, const int vbrsf[SFBMAX],\n                      const int vbrsfmin[SFBMAX], int vbrmax)\n{\n    gr_info *const cod_info = that->cod_info;\n    lame_internal_flags const *const gfc = that->gfc;\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int const maxminsfb = that->mingain_l;\n    int     mover, maxover0 = 0, maxover1 = 0, delta = 0;\n    int     v, v0, v1;\n    int     sfb;\n    int const psymax = cod_info->psymax;\n\n    for (sfb = 0; sfb < psymax; ++sfb) {\n        assert(vbrsf[sfb] >= vbrsfmin[sfb]);\n        v = vbrmax - vbrsf[sfb];\n        if (delta < v) {\n            delta = v;\n        }\n        v0 = v - (4 * 14 + 2 * max_range_short[sfb]);\n        v1 = v - (4 * 14 + 4 * max_range_short[sfb]);\n        if (maxover0 < v0) {\n            maxover0 = v0;\n        }\n        if (maxover1 < v1) {\n            maxover1 = v1;\n        }\n    }\n    if (cfg->noise_shaping == 2) {\n        /* allow scalefac_scale=1 */\n        mover = Min(maxover0, maxover1);\n    }\n    else {\n        mover = maxover0;\n    }\n    if (delta > mover) {\n        delta = mover;\n    }\n    vbrmax -= delta;\n    maxover0 -= mover;\n    maxover1 -= mover;\n\n    if (maxover0 == 0) {\n        cod_info->scalefac_scale = 0;\n    }\n    else if (maxover1 == 0) {\n        cod_info->scalefac_scale = 1;\n    }\n    if (vbrmax < maxminsfb) {\n        vbrmax = maxminsfb;\n    }\n    cod_info->global_gain = vbrmax;\n\n    if (cod_info->global_gain < 0) {\n        cod_info->global_gain = 0;\n    }\n    else if (cod_info->global_gain > 255) {\n        cod_info->global_gain = 255;\n    }\n    {\n        int     sf_temp[SFBMAX];\n        for (sfb = 0; sfb < SFBMAX; ++sfb) {\n            sf_temp[sfb] = vbrsf[sfb] - vbrmax;\n        }\n        set_subblock_gain(cod_info, &that->mingain_s[0], sf_temp);\n        set_scalefacs(cod_info, vbrsfmin, sf_temp, max_range_short);\n    }\n    assert(checkScalefactor(cod_info, vbrsfmin));\n}\n\n\n\n/******************************************************************\n *\n *  long block scalefacs\n *\n ******************************************************************/\n\nstatic void\nlong_block_constrain(const algo_t * that, const int vbrsf[SFBMAX], const int vbrsfmin[SFBMAX],\n                     int vbrmax)\n{\n    gr_info *const cod_info = that->cod_info;\n    lame_internal_flags const *const gfc = that->gfc;\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    uint8_t const *max_rangep;\n    int const maxminsfb = that->mingain_l;\n    int     sfb;\n    int     maxover0, maxover1, maxover0p, maxover1p, mover, delta = 0;\n    int     v, v0, v1, v0p, v1p, vm0p = 1, vm1p = 1;\n    int const psymax = cod_info->psymax;\n\n    max_rangep = cfg->mode_gr == 2 ? max_range_long : max_range_long_lsf_pretab;\n\n    maxover0 = 0;\n    maxover1 = 0;\n    maxover0p = 0;      /* pretab */\n    maxover1p = 0;      /* pretab */\n\n    for (sfb = 0; sfb < psymax; ++sfb) {\n        assert(vbrsf[sfb] >= vbrsfmin[sfb]);\n        v = vbrmax - vbrsf[sfb];\n        if (delta < v) {\n            delta = v;\n        }\n        v0 = v - 2 * max_range_long[sfb];\n        v1 = v - 4 * max_range_long[sfb];\n        v0p = v - 2 * (max_rangep[sfb] + pretab[sfb]);\n        v1p = v - 4 * (max_rangep[sfb] + pretab[sfb]);\n        if (maxover0 < v0) {\n            maxover0 = v0;\n        }\n        if (maxover1 < v1) {\n            maxover1 = v1;\n        }\n        if (maxover0p < v0p) {\n            maxover0p = v0p;\n        }\n        if (maxover1p < v1p) {\n            maxover1p = v1p;\n        }\n    }\n    if (vm0p == 1) {\n        int     gain = vbrmax - maxover0p;\n        if (gain < maxminsfb) {\n            gain = maxminsfb;\n        }\n        for (sfb = 0; sfb < psymax; ++sfb) {\n            int const a = (gain - vbrsfmin[sfb]) - 2 * pretab[sfb];\n            if (a <= 0) {\n                vm0p = 0;\n                vm1p = 0;\n                break;\n            }\n        }\n    }\n    if (vm1p == 1) {\n        int     gain = vbrmax - maxover1p;\n        if (gain < maxminsfb) {\n            gain = maxminsfb;\n        }\n        for (sfb = 0; sfb < psymax; ++sfb) {\n            int const b = (gain - vbrsfmin[sfb]) - 4 * pretab[sfb];\n            if (b <= 0) {\n                vm1p = 0;\n                break;\n            }\n        }\n    }\n    if (vm0p == 0) {\n        maxover0p = maxover0;\n    }\n    if (vm1p == 0) {\n        maxover1p = maxover1;\n    }\n    if (cfg->noise_shaping != 2) {\n        maxover1 = maxover0;\n        maxover1p = maxover0p;\n    }\n    mover = Min(maxover0, maxover0p);\n    mover = Min(mover, maxover1);\n    mover = Min(mover, maxover1p);\n\n    if (delta > mover) {\n        delta = mover;\n    }\n    vbrmax -= delta;\n    if (vbrmax < maxminsfb) {\n        vbrmax = maxminsfb;\n    }\n    maxover0 -= mover;\n    maxover0p -= mover;\n    maxover1 -= mover;\n    maxover1p -= mover;\n\n    if (maxover0 == 0) {\n        cod_info->scalefac_scale = 0;\n        cod_info->preflag = 0;\n        max_rangep = max_range_long;\n    }\n    else if (maxover0p == 0) {\n        cod_info->scalefac_scale = 0;\n        cod_info->preflag = 1;\n    }\n    else if (maxover1 == 0) {\n        cod_info->scalefac_scale = 1;\n        cod_info->preflag = 0;\n        max_rangep = max_range_long;\n    }\n    else if (maxover1p == 0) {\n        cod_info->scalefac_scale = 1;\n        cod_info->preflag = 1;\n    }\n    else {\n        assert(0);      /* this should not happen */\n    }\n    cod_info->global_gain = vbrmax;\n    if (cod_info->global_gain < 0) {\n        cod_info->global_gain = 0;\n    }\n    else if (cod_info->global_gain > 255) {\n        cod_info->global_gain = 255;\n    }\n    {\n        int     sf_temp[SFBMAX];\n        for (sfb = 0; sfb < SFBMAX; ++sfb) {\n            sf_temp[sfb] = vbrsf[sfb] - vbrmax;\n        }\n        set_scalefacs(cod_info, vbrsfmin, sf_temp, max_rangep);\n    }\n    assert(checkScalefactor(cod_info, vbrsfmin));\n}\n\n\n\nstatic void\nbitcount(const algo_t * that)\n{\n    int     rc = scale_bitcount(that->gfc, that->cod_info);\n\n    if (rc == 0) {\n        return;\n    }\n    /*  this should not happen due to the way the scalefactors are selected  */\n    ERRORF(that->gfc, \"INTERNAL ERROR IN VBR NEW CODE (986), please send bug report\\n\");\n    exit(-1);\n}\n\n\n\nstatic int\nquantizeAndCountBits(const algo_t * that)\n{\n    quantize_x34(that);\n    that->cod_info->part2_3_length = noquant_count_bits(that->gfc, that->cod_info, 0);\n    return that->cod_info->part2_3_length;\n}\n\n\n\n\n\nstatic int\ntryGlobalStepsize(const algo_t * that, const int sfwork[SFBMAX],\n                  const int vbrsfmin[SFBMAX], int delta)\n{\n    FLOAT const xrpow_max = that->cod_info->xrpow_max;\n    int     sftemp[SFBMAX], i, nbits;\n    int     gain, vbrmax = 0;\n    for (i = 0; i < SFBMAX; ++i) {\n        gain = sfwork[i] + delta;\n        if (gain < vbrsfmin[i]) {\n            gain = vbrsfmin[i];\n        }\n        if (gain > 255) {\n            gain = 255;\n        }\n        if (vbrmax < gain) {\n            vbrmax = gain;\n        }\n        sftemp[i] = gain;\n    }\n    that->alloc(that, sftemp, vbrsfmin, vbrmax);\n    bitcount(that);\n    nbits = quantizeAndCountBits(that);\n    that->cod_info->xrpow_max = xrpow_max;\n    return nbits;\n}\n\n\n\nstatic void\nsearchGlobalStepsizeMax(const algo_t * that, const int sfwork[SFBMAX],\n                        const int vbrsfmin[SFBMAX], int target)\n{\n    gr_info const *const cod_info = that->cod_info;\n    const int gain = cod_info->global_gain;\n    int     curr = gain;\n    int     gain_ok = 1024;\n    int     nbits = LARGE_BITS;\n    int     l = gain, r = 512;\n\n    assert(gain >= 0);\n    while (l <= r) {\n        curr = (l + r) >> 1;\n        nbits = tryGlobalStepsize(that, sfwork, vbrsfmin, curr - gain);\n        if (nbits == 0 || (nbits + cod_info->part2_length) < target) {\n            r = curr - 1;\n            gain_ok = curr;\n        }\n        else {\n            l = curr + 1;\n            if (gain_ok == 1024) {\n                gain_ok = curr;\n            }\n        }\n    }\n    if (gain_ok != curr) {\n        curr = gain_ok;\n        nbits = tryGlobalStepsize(that, sfwork, vbrsfmin, curr - gain);\n    }\n}\n\n\n\nstatic int\nsfDepth(const int sfwork[SFBMAX])\n{\n    int     m = 0;\n    unsigned int i, j;\n    for (j = SFBMAX, i = 0; j > 0; --j, ++i) {\n        int const di = 255 - sfwork[i];\n        if (m < di) {\n            m = di;\n        }\n        assert(sfwork[i] >= 0);\n        assert(sfwork[i] <= 255);\n    }\n    assert(m >= 0);\n    assert(m <= 255);\n    return m;\n}\n\n\nstatic void\ncutDistribution(const int sfwork[SFBMAX], int sf_out[SFBMAX], int cut)\n{\n    unsigned int i, j;\n    for (j = SFBMAX, i = 0; j > 0; --j, ++i) {\n        int const x = sfwork[i];\n        sf_out[i] = x < cut ? x : cut;\n    }\n}\n\n\nstatic int\nflattenDistribution(const int sfwork[SFBMAX], int sf_out[SFBMAX], int dm, int k, int p)\n{\n    unsigned int i, j;\n    int     x, sfmax = 0;\n    if (dm > 0) {\n        for (j = SFBMAX, i = 0; j > 0; --j, ++i) {\n            int const di = p - sfwork[i];\n            x = sfwork[i] + (k * di) / dm;\n            if (x < 0) {\n                x = 0;\n            }\n            else {\n                if (x > 255) {\n                    x = 255;\n                }\n            }\n            sf_out[i] = x;\n            if (sfmax < x) {\n                sfmax = x;\n            }\n        }\n    }\n    else {\n        for (j = SFBMAX, i = 0; j > 0u; --j, ++i) {\n            x = sfwork[i];\n            sf_out[i] = x;\n            if (sfmax < x) {\n                sfmax = x;\n            }\n        }\n    }\n    return sfmax;\n}\n\n\nstatic int\ntryThatOne(algo_t const* that, const int sftemp[SFBMAX], const int vbrsfmin[SFBMAX], int vbrmax)\n{\n    FLOAT const xrpow_max = that->cod_info->xrpow_max;\n    int     nbits = LARGE_BITS;\n    that->alloc(that, sftemp, vbrsfmin, vbrmax);\n    bitcount(that);\n    nbits = quantizeAndCountBits(that);\n    nbits += that->cod_info->part2_length;\n    that->cod_info->xrpow_max = xrpow_max;\n    return nbits;\n}\n\n\nstatic void\noutOfBitsStrategy(algo_t const* that, const int sfwork[SFBMAX], const int vbrsfmin[SFBMAX], int target)\n{\n    int     wrk[SFBMAX];\n    int const dm = sfDepth(sfwork);\n    int const p = that->cod_info->global_gain;\n    int     nbits;\n\n    /* PART 1 */\n    {\n        int     bi = dm / 2;\n        int     bi_ok = -1;\n        int     bu = 0;\n        int     bo = dm;\n        for (;;) {\n            int const sfmax = flattenDistribution(sfwork, wrk, dm, bi, p);\n            nbits = tryThatOne(that, wrk, vbrsfmin, sfmax);\n            if (nbits <= target) {\n                bi_ok = bi;\n                bo = bi - 1;\n            }\n            else {\n                bu = bi + 1;\n            }\n            if (bu <= bo) {\n                bi = (bu + bo) / 2;\n            }\n            else {\n                break;\n            }\n        }\n        if (bi_ok >= 0) {\n            if (bi != bi_ok) {\n                int const sfmax = flattenDistribution(sfwork, wrk, dm, bi_ok, p);\n                nbits = tryThatOne(that, wrk, vbrsfmin, sfmax);\n            }\n            return;\n        }\n    }\n\n    /* PART 2: */\n    {\n        int     bi = (255 + p) / 2;\n        int     bi_ok = -1;\n        int     bu = p;\n        int     bo = 255;\n        for (;;) {\n            int const sfmax = flattenDistribution(sfwork, wrk, dm, dm, bi);\n            nbits = tryThatOne(that, wrk, vbrsfmin, sfmax);\n            if (nbits <= target) {\n                bi_ok = bi;\n                bo = bi - 1;\n            }\n            else {\n                bu = bi + 1;\n            }\n            if (bu <= bo) {\n                bi = (bu + bo) / 2;\n            }\n            else {\n                break;\n            }\n        }\n        if (bi_ok >= 0) {\n            if (bi != bi_ok) {\n                int const sfmax = flattenDistribution(sfwork, wrk, dm, dm, bi_ok);\n                nbits = tryThatOne(that, wrk, vbrsfmin, sfmax);\n            }\n            return;\n        }\n    }\n\n    /* fall back to old code, likely to be never called */\n    searchGlobalStepsizeMax(that, wrk, vbrsfmin, target);\n}\n\n\nstatic int\nreduce_bit_usage(lame_internal_flags * gfc, int gr, int ch\n#if 0\n                 , const FLOAT xr34orig[576], const FLOAT l3_xmin[SFBMAX], int maxbits\n#endif\n    )\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    gr_info *const cod_info = &gfc->l3_side.tt[gr][ch];\n    /*  try some better scalefac storage\n     */\n    best_scalefac_store(gfc, gr, ch, &gfc->l3_side);\n\n    /*  best huffman_divide may save some bits too\n     */\n    if (cfg->use_best_huffman == 1)\n        best_huffman_divide(gfc, cod_info);\n    return cod_info->part2_3_length + cod_info->part2_length;\n}\n\n\n\n\nint\nVBR_encode_frame(lame_internal_flags * gfc, const FLOAT xr34orig[2][2][576],\n                 const FLOAT l3_xmin[2][2][SFBMAX], const int max_bits[2][2])\n{\n    SessionConfig_t const *const cfg = &gfc->cfg;\n    int     sfwork_[2][2][SFBMAX];\n    int     vbrsfmin_[2][2][SFBMAX];\n    algo_t  that_[2][2];\n    int const ngr = cfg->mode_gr;\n    int const nch = cfg->channels_out;\n    int     max_nbits_ch[2][2] = {{0, 0}, {0 ,0}};\n    int     max_nbits_gr[2] = {0, 0};\n    int     max_nbits_fr = 0;\n    int     use_nbits_ch[2][2] = {{MAX_BITS_PER_CHANNEL+1, MAX_BITS_PER_CHANNEL+1}\n                                 ,{MAX_BITS_PER_CHANNEL+1, MAX_BITS_PER_CHANNEL+1}};\n    int     use_nbits_gr[2] = { MAX_BITS_PER_GRANULE+1, MAX_BITS_PER_GRANULE+1 };\n    int     use_nbits_fr = MAX_BITS_PER_GRANULE+MAX_BITS_PER_GRANULE;\n    int     gr, ch;\n    int     ok, sum_fr;\n\n    /* set up some encoding parameters\n     */\n    for (gr = 0; gr < ngr; ++gr) {\n        max_nbits_gr[gr] = 0;\n        for (ch = 0; ch < nch; ++ch) {\n            max_nbits_ch[gr][ch] = max_bits[gr][ch];\n            use_nbits_ch[gr][ch] = 0;\n            max_nbits_gr[gr] += max_bits[gr][ch];\n            max_nbits_fr += max_bits[gr][ch];\n            that_[gr][ch].find = (cfg->full_outer_loop < 0) ? guess_scalefac_x34 : find_scalefac_x34;\n            that_[gr][ch].gfc = gfc;\n            that_[gr][ch].cod_info = &gfc->l3_side.tt[gr][ch];\n            that_[gr][ch].xr34orig = xr34orig[gr][ch];\n            if (that_[gr][ch].cod_info->block_type == SHORT_TYPE) {\n                that_[gr][ch].alloc = short_block_constrain;\n            }\n            else {\n                that_[gr][ch].alloc = long_block_constrain;\n            }\n        }               /* for ch */\n    }\n    /* searches scalefactors\n     */\n    for (gr = 0; gr < ngr; ++gr) {\n        for (ch = 0; ch < nch; ++ch) {\n            if (max_bits[gr][ch] > 0) {\n                algo_t *that = &that_[gr][ch];\n                int    *sfwork = sfwork_[gr][ch];\n                int    *vbrsfmin = vbrsfmin_[gr][ch];\n                int     vbrmax;\n\n                vbrmax = block_sf(that, l3_xmin[gr][ch], sfwork, vbrsfmin);\n                that->alloc(that, sfwork, vbrsfmin, vbrmax);\n                bitcount(that);\n            }\n            else {\n                /*  xr contains no energy \n                 *  l3_enc, our encoding data, will be quantized to zero\n                 *  continue with next channel\n                 */\n            }\n        }               /* for ch */\n    }\n    /* encode 'as is'\n     */\n    use_nbits_fr = 0;\n    for (gr = 0; gr < ngr; ++gr) {\n        use_nbits_gr[gr] = 0;\n        for (ch = 0; ch < nch; ++ch) {\n            algo_t const *that = &that_[gr][ch];\n            if (max_bits[gr][ch] > 0) {\n                memset(&that->cod_info->l3_enc[0], 0, sizeof(that->cod_info->l3_enc));\n                (void) quantizeAndCountBits(that);\n            }\n            else {\n                /*  xr contains no energy \n                 *  l3_enc, our encoding data, will be quantized to zero\n                 *  continue with next channel\n                 */\n            }\n            use_nbits_ch[gr][ch] = reduce_bit_usage(gfc, gr, ch);\n            use_nbits_gr[gr] += use_nbits_ch[gr][ch];\n        }               /* for ch */\n        use_nbits_fr += use_nbits_gr[gr];\n    }\n\n    /* check bit constrains\n     */\n    if (use_nbits_fr <= max_nbits_fr) {\n        ok = 1;\n        for (gr = 0; gr < ngr; ++gr) {\n            if (use_nbits_gr[gr] > MAX_BITS_PER_GRANULE) {\n                /* violates the rule that every granule has to use no more\n                 * bits than MAX_BITS_PER_GRANULE\n                 */\n                ok = 0;\n            }\n            for (ch = 0; ch < nch; ++ch) {\n                if (use_nbits_ch[gr][ch] > MAX_BITS_PER_CHANNEL) {\n                    /* violates the rule that every gr_ch has to use no more\n                     * bits than MAX_BITS_PER_CHANNEL\n                     *\n                     * This isn't explicitly stated in the ISO docs, but the\n                     * part2_3_length field has only 12 bits, that makes it\n                     * up to a maximum size of 4095 bits!!!\n                     */\n                    ok = 0;\n                }\n            }\n        }\n        if (ok) {\n            return use_nbits_fr;\n        }\n    }\n    \n    /* OK, we are in trouble and have to define how many bits are\n     * to be used for each granule\n     */\n    {\n        ok = 1;\n        sum_fr = 0;\n\n        for (gr = 0; gr < ngr; ++gr) {\n            max_nbits_gr[gr] = 0;\n            for (ch = 0; ch < nch; ++ch) {\n                if (use_nbits_ch[gr][ch] > MAX_BITS_PER_CHANNEL) {\n                    max_nbits_ch[gr][ch] = MAX_BITS_PER_CHANNEL;\n                }\n                else {\n                    max_nbits_ch[gr][ch] = use_nbits_ch[gr][ch];\n                }\n                max_nbits_gr[gr] += max_nbits_ch[gr][ch];\n            }\n            if (max_nbits_gr[gr] > MAX_BITS_PER_GRANULE) {\n                float   f[2] = {0.0f, 0.0f}, s = 0.0f;\n                for (ch = 0; ch < nch; ++ch) {\n                    if (max_nbits_ch[gr][ch] > 0) {\n                        f[ch] = sqrt(sqrt(max_nbits_ch[gr][ch]));\n                        s += f[ch];\n                    }\n                    else {\n                        f[ch] = 0;\n                    }\n                }\n                for (ch = 0; ch < nch; ++ch) {\n                    if (s > 0) {\n                        max_nbits_ch[gr][ch] = MAX_BITS_PER_GRANULE * f[ch] / s;\n                    }\n                    else {\n                        max_nbits_ch[gr][ch] = 0;\n                    }\n                }\n                if (nch > 1) {\n                    if (max_nbits_ch[gr][0] > use_nbits_ch[gr][0] + 32) {\n                        max_nbits_ch[gr][1] += max_nbits_ch[gr][0];\n                        max_nbits_ch[gr][1] -= use_nbits_ch[gr][0] + 32;\n                        max_nbits_ch[gr][0] = use_nbits_ch[gr][0] + 32;\n                    }\n                    if (max_nbits_ch[gr][1] > use_nbits_ch[gr][1] + 32) {\n                        max_nbits_ch[gr][0] += max_nbits_ch[gr][1];\n                        max_nbits_ch[gr][0] -= use_nbits_ch[gr][1] + 32;\n                        max_nbits_ch[gr][1] = use_nbits_ch[gr][1] + 32;\n                    }\n                    if (max_nbits_ch[gr][0] > MAX_BITS_PER_CHANNEL) {\n                        max_nbits_ch[gr][0] = MAX_BITS_PER_CHANNEL;\n                    }\n                    if (max_nbits_ch[gr][1] > MAX_BITS_PER_CHANNEL) {\n                        max_nbits_ch[gr][1] = MAX_BITS_PER_CHANNEL;\n                    }\n                }\n                max_nbits_gr[gr] = 0;\n                for (ch = 0; ch < nch; ++ch) {\n                    max_nbits_gr[gr] += max_nbits_ch[gr][ch];\n                }\n            }\n            sum_fr += max_nbits_gr[gr];\n        }\n        if (sum_fr > max_nbits_fr) {\n            {\n                float   f[2] = {0.0f, 0.0f}, s = 0.0f;\n                for (gr = 0; gr < ngr; ++gr) {\n                    if (max_nbits_gr[gr] > 0) {\n                        f[gr] = sqrt(max_nbits_gr[gr]);\n                        s += f[gr];\n                    }\n                    else {\n                        f[gr] = 0;\n                    }\n                }\n                for (gr = 0; gr < ngr; ++gr) {\n                    if (s > 0) {\n                        max_nbits_gr[gr] = max_nbits_fr * f[gr] / s;\n                    }\n                    else {\n                        max_nbits_gr[gr] = 0;\n                    }\n                }\n            }\n            if (ngr > 1) {\n                if (max_nbits_gr[0] > use_nbits_gr[0] + 125) {\n                    max_nbits_gr[1] += max_nbits_gr[0];\n                    max_nbits_gr[1] -= use_nbits_gr[0] + 125;\n                    max_nbits_gr[0] = use_nbits_gr[0] + 125;\n                }\n                if (max_nbits_gr[1] > use_nbits_gr[1] + 125) {\n                    max_nbits_gr[0] += max_nbits_gr[1];\n                    max_nbits_gr[0] -= use_nbits_gr[1] + 125;\n                    max_nbits_gr[1] = use_nbits_gr[1] + 125;\n                }\n                for (gr = 0; gr < ngr; ++gr) {\n                    if (max_nbits_gr[gr] > MAX_BITS_PER_GRANULE) {\n                        max_nbits_gr[gr] = MAX_BITS_PER_GRANULE;\n                    }\n                }\n            }\n            for (gr = 0; gr < ngr; ++gr) {\n                float   f[2] = {0.0f, 0.0f}, s = 0.0f;\n                for (ch = 0; ch < nch; ++ch) {\n                    if (max_nbits_ch[gr][ch] > 0) {\n                        f[ch] = sqrt(max_nbits_ch[gr][ch]);\n                        s += f[ch];\n                    }\n                    else {\n                        f[ch] = 0;\n                    }\n                }\n                for (ch = 0; ch < nch; ++ch) {\n                    if (s > 0) {\n                        max_nbits_ch[gr][ch] = max_nbits_gr[gr] * f[ch] / s;\n                    }\n                    else {\n                        max_nbits_ch[gr][ch] = 0;\n                    }\n                }\n                if (nch > 1) {\n                    if (max_nbits_ch[gr][0] > use_nbits_ch[gr][0] + 32) {\n                        max_nbits_ch[gr][1] += max_nbits_ch[gr][0];\n                        max_nbits_ch[gr][1] -= use_nbits_ch[gr][0] + 32;\n                        max_nbits_ch[gr][0] = use_nbits_ch[gr][0] + 32;\n                    }\n                    if (max_nbits_ch[gr][1] > use_nbits_ch[gr][1] + 32) {\n                        max_nbits_ch[gr][0] += max_nbits_ch[gr][1];\n                        max_nbits_ch[gr][0] -= use_nbits_ch[gr][1] + 32;\n                        max_nbits_ch[gr][1] = use_nbits_ch[gr][1] + 32;\n                    }\n                    for (ch = 0; ch < nch; ++ch) {\n                        if (max_nbits_ch[gr][ch] > MAX_BITS_PER_CHANNEL) {\n                            max_nbits_ch[gr][ch] = MAX_BITS_PER_CHANNEL;\n                        }\n                    }\n                }\n            }\n        }\n        /* sanity check */\n        sum_fr = 0;\n        for (gr = 0; gr < ngr; ++gr) {\n            int     sum_gr = 0;\n            for (ch = 0; ch < nch; ++ch) {\n                sum_gr += max_nbits_ch[gr][ch];\n                if (max_nbits_ch[gr][ch] > MAX_BITS_PER_CHANNEL) {\n                    ok = 0;\n                }\n            }\n            sum_fr += sum_gr;\n            if (sum_gr > MAX_BITS_PER_GRANULE) {\n                ok = 0;\n            }\n        }\n        if (sum_fr > max_nbits_fr) {\n            ok = 0;\n        }\n        if (!ok) {\n            /* we must have done something wrong, fallback to 'on_pe' based constrain */\n            for (gr = 0; gr < ngr; ++gr) {\n                for (ch = 0; ch < nch; ++ch) {\n                    max_nbits_ch[gr][ch] = max_bits[gr][ch];\n                }\n            }\n        }\n    }\n\n    /* we already called the 'best_scalefac_store' function, so we need to reset some\n     * variables before we can do it again.\n     */\n    for (ch = 0; ch < nch; ++ch) {\n        gfc->l3_side.scfsi[ch][0] = 0;\n        gfc->l3_side.scfsi[ch][1] = 0;\n        gfc->l3_side.scfsi[ch][2] = 0;\n        gfc->l3_side.scfsi[ch][3] = 0;\n    }\n    for (gr = 0; gr < ngr; ++gr) {\n        for (ch = 0; ch < nch; ++ch) {\n            gfc->l3_side.tt[gr][ch].scalefac_compress = 0;\n        }\n    }\n\n    /* alter our encoded data, until it fits into the target bitrate\n     */\n    use_nbits_fr = 0;\n    for (gr = 0; gr < ngr; ++gr) {\n        use_nbits_gr[gr] = 0;\n        for (ch = 0; ch < nch; ++ch) {\n            algo_t const *that = &that_[gr][ch];\n            use_nbits_ch[gr][ch] = 0;\n            if (max_bits[gr][ch] > 0) {\n                int    *sfwork = sfwork_[gr][ch];\n                int const *vbrsfmin = vbrsfmin_[gr][ch];\n                cutDistribution(sfwork, sfwork, that->cod_info->global_gain);\n                outOfBitsStrategy(that, sfwork, vbrsfmin, max_nbits_ch[gr][ch]);\n            }\n            use_nbits_ch[gr][ch] = reduce_bit_usage(gfc, gr, ch);\n            assert(use_nbits_ch[gr][ch] <= max_nbits_ch[gr][ch]);\n            use_nbits_gr[gr] += use_nbits_ch[gr][ch];\n        }               /* for ch */\n        use_nbits_fr += use_nbits_gr[gr];\n    }\n\n    /* check bit constrains, but it should always be ok, iff there are no bugs ;-)\n     */\n    if (use_nbits_fr <= max_nbits_fr) {\n        return use_nbits_fr;\n    }\n\n    ERRORF(gfc, \"INTERNAL ERROR IN VBR NEW CODE (1313), please send bug report\\n\"\n           \"maxbits=%d usedbits=%d\\n\", max_nbits_fr, use_nbits_fr);\n    exit(-1);\n}\n"
  },
  {
    "path": "app/jni/libmp3lame/vbrquantize.h",
    "content": "/*\n * MP3 VBR quantization\n *\n * Copyright (c) 1999 Mark Taylor\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_VBRQUANTIZE_H\n#define LAME_VBRQUANTIZE_H\n\nint     VBR_encode_frame(lame_internal_flags * gfc, const FLOAT xr34orig[2][2][576],\n                         const FLOAT l3_xmin[2][2][SFBMAX], const int maxbits[2][2]);\n\n#endif /* LAME_VBRQUANTIZE_H */\n"
  },
  {
    "path": "app/jni/libmp3lame/vector/Makefile.am",
    "content": "## $Id: Makefile.am,v 1.1 2007/01/09 10:15:53 aleidinger Exp $\n\ninclude $(top_srcdir)/Makefile.am.global\n\nif WITH_XMM\nnoinst_LTLIBRARIES = liblamevectorroutines.la\nendif\n\n##liblamecpuroutines_la_LIBADD = \n##liblamecpuroutines_la_LDFLAGS =\n\nINCLUDES = @INCLUDES@ \\\n\t-I$(top_srcdir)/libmp3lame \\\n\t-I$(top_srcdir)/mpglib \\\n\t-I$(top_builddir)\n\nDEFS = @DEFS@ @CONFIG_DEFS@\n\nxmm_sources = xmm_quantize_sub.c\n\nif WITH_XMM\nliblamevectorroutines_la_SOURCES = $(xmm_sources)\nendif\n\nnoinst_HEADERS = lame_intrin.h\n\nEXTRA_liblamevectorroutines_la_SOURCES = $(xmm_sources)\n\nCLEANFILES = lclint.txt\n\nLCLINTFLAGS= \\\n\t+posixlib \\\n\t+showsummary \\\n\t+showalluses \\\n\t+whichlib \\\n\t+forcehints \\\n\t-fixedformalarray \\\n\t+matchanyintegral \\\n\t-Dlint\n\nlclint.txt: ${liblamecpuroutines_la_SOURCES} ${noinst_HEADERS}\n\t@lclint ${LCLINTFLAGS} ${INCLUDES} ${DEFS} ${liblamecpuroutines_la_SOURCES} 2>&1 >lclint.txt || true\n\nlclint: lclint.txt\n\tmore lclint.txt\n\n#$(OBJECTS): libtool\n#libtool: $(LIBTOOL_DEPS)\n#\t$(SHELL) $(top_builddir)/config.status --recheck\n"
  },
  {
    "path": "app/jni/libmp3lame/vector/Makefile.in",
    "content": "# Makefile.in generated by automake 1.11.1 from Makefile.am.\n# @configure_input@\n\n# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,\n# 2003, 2004, 2005, 2006, 2007, 2008, 2009  Free Software Foundation,\n# Inc.\n# This Makefile.in is free software; the Free Software Foundation\n# gives unlimited permission to copy and/or distribute it,\n# with or without modifications, as long as this notice is preserved.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY, to the extent permitted by law; without\n# even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n# PARTICULAR PURPOSE.\n\n@SET_MAKE@\n\n# global section for every Makefile.am\n\n\nVPATH = @srcdir@\npkgdatadir = $(datadir)/@PACKAGE@\npkgincludedir = $(includedir)/@PACKAGE@\npkglibdir = $(libdir)/@PACKAGE@\npkglibexecdir = $(libexecdir)/@PACKAGE@\nam__cd = CDPATH=\"$${ZSH_VERSION+.}$(PATH_SEPARATOR)\" && cd\ninstall_sh_DATA = $(install_sh) -c -m 644\ninstall_sh_PROGRAM = $(install_sh) -c\ninstall_sh_SCRIPT = $(install_sh) -c\nINSTALL_HEADER = $(INSTALL_DATA)\ntransform = $(program_transform_name)\nNORMAL_INSTALL = :\nPRE_INSTALL = :\nPOST_INSTALL = :\nNORMAL_UNINSTALL = :\nPRE_UNINSTALL = :\nPOST_UNINSTALL = :\nbuild_triplet = @build@\nhost_triplet = @host@\nANSI2KNR = $(top_srcdir)/ansi2knr\nDIST_COMMON = $(noinst_HEADERS) $(srcdir)/Makefile.am \\\n\t$(srcdir)/Makefile.in $(top_srcdir)/Makefile.am.global\nsubdir = libmp3lame/vector\nACLOCAL_M4 = $(top_srcdir)/aclocal.m4\nam__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \\\n\t$(top_srcdir)/configure.in\nam__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \\\n\t$(ACLOCAL_M4)\nmkinstalldirs = $(install_sh) -d\nCONFIG_HEADER = $(top_builddir)/config.h\nCONFIG_CLEAN_FILES =\nCONFIG_CLEAN_VPATH_FILES =\nLTLIBRARIES = $(noinst_LTLIBRARIES)\nliblamevectorroutines_la_LIBADD =\nam__liblamevectorroutines_la_SOURCES_DIST = xmm_quantize_sub.c\nam__objects_1 = xmm_quantize_sub$U.lo\n@WITH_XMM_TRUE@am_liblamevectorroutines_la_OBJECTS = $(am__objects_1)\nliblamevectorroutines_la_OBJECTS =  \\\n\t$(am_liblamevectorroutines_la_OBJECTS)\n@WITH_XMM_TRUE@am_liblamevectorroutines_la_rpath =\nDEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)\ndepcomp = $(SHELL) $(top_srcdir)/depcomp\nam__depfiles_maybe = depfiles\nam__mv = mv -f\nCOMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \\\n\t$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)\nLTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \\\n\t--mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \\\n\t$(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)\nCCLD = $(CC)\nLINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \\\n\t--mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \\\n\t$(LDFLAGS) -o $@\nSOURCES = $(liblamevectorroutines_la_SOURCES) \\\n\t$(EXTRA_liblamevectorroutines_la_SOURCES)\nDIST_SOURCES = $(am__liblamevectorroutines_la_SOURCES_DIST) \\\n\t$(EXTRA_liblamevectorroutines_la_SOURCES)\nHEADERS = $(noinst_HEADERS)\nETAGS = etags\nCTAGS = ctags\nDISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)\nACLOCAL = @ACLOCAL@\nALLOCA = @ALLOCA@\nAMTAR = @AMTAR@\nAR = @AR@\nAUTOCONF = @AUTOCONF@\nAUTOHEADER = @AUTOHEADER@\nAUTOMAKE = @AUTOMAKE@\nAWK = @AWK@\nCC = @CC@\nCCDEPMODE = @CCDEPMODE@\nCFLAGS = @CFLAGS@\nCONFIG_DEFS = @CONFIG_DEFS@\nCONFIG_MATH_LIB = @CONFIG_MATH_LIB@\nCPP = @CPP@\nCPPFLAGS = @CPPFLAGS@\nCPUCCODE = @CPUCCODE@\nCPUTYPE = @CPUTYPE@\nCYGPATH_W = @CYGPATH_W@\nDEFS = @DEFS@ @CONFIG_DEFS@\nDEPDIR = @DEPDIR@\nDSYMUTIL = @DSYMUTIL@\nDUMPBIN = @DUMPBIN@\nECHO_C = @ECHO_C@\nECHO_N = @ECHO_N@\nECHO_T = @ECHO_T@\nEGREP = @EGREP@\nEXEEXT = @EXEEXT@\nFGREP = @FGREP@\nFRONTEND_CFLAGS = @FRONTEND_CFLAGS@\nFRONTEND_LDADD = @FRONTEND_LDADD@\nFRONTEND_LDFLAGS = @FRONTEND_LDFLAGS@\nGREP = @GREP@\nGTK_CFLAGS = @GTK_CFLAGS@\nGTK_CONFIG = @GTK_CONFIG@\nGTK_LIBS = @GTK_LIBS@\nINCLUDES = @INCLUDES@ \\\n\t-I$(top_srcdir)/libmp3lame \\\n\t-I$(top_srcdir)/mpglib \\\n\t-I$(top_builddir)\n\nINSTALL = @INSTALL@\nINSTALL_DATA = @INSTALL_DATA@\nINSTALL_PROGRAM = @INSTALL_PROGRAM@\nINSTALL_SCRIPT = @INSTALL_SCRIPT@\nINSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@\nLD = @LD@\nLDADD = @LDADD@\nLDFLAGS = @LDFLAGS@\nLIBICONV = @LIBICONV@\nLIBOBJS = @LIBOBJS@\nLIBS = @LIBS@\nLIBTOOL = @LIBTOOL@\nLIBTOOL_DEPS = @LIBTOOL_DEPS@\nLIB_MAJOR_VERSION = @LIB_MAJOR_VERSION@\nLIB_MINOR_VERSION = @LIB_MINOR_VERSION@\nLIPO = @LIPO@\nLN_S = @LN_S@\nLTLIBICONV = @LTLIBICONV@\nLTLIBOBJS = @LTLIBOBJS@\nMAINT = @MAINT@\nMAKEDEP = @MAKEDEP@\nMAKEINFO = @MAKEINFO@\nMKDIR_P = @MKDIR_P@\nNASM = @NASM@\nNASM_FORMAT = @NASM_FORMAT@\nNM = @NM@\nNMEDIT = @NMEDIT@\nOBJDUMP = @OBJDUMP@\nOBJEXT = @OBJEXT@\nOTOOL = @OTOOL@\nOTOOL64 = @OTOOL64@\nPACKAGE = @PACKAGE@\nPACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@\nPACKAGE_NAME = @PACKAGE_NAME@\nPACKAGE_STRING = @PACKAGE_STRING@\nPACKAGE_TARNAME = @PACKAGE_TARNAME@\nPACKAGE_URL = @PACKAGE_URL@\nPACKAGE_VERSION = @PACKAGE_VERSION@\nPATH_SEPARATOR = @PATH_SEPARATOR@\nPKG_CONFIG = @PKG_CONFIG@\nPKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@\nPKG_CONFIG_PATH = @PKG_CONFIG_PATH@\nRANLIB = @RANLIB@\nRM_F = @RM_F@\nSED = @SED@\nSET_MAKE = @SET_MAKE@\nSHELL = @SHELL@\nSNDFILE_CFLAGS = @SNDFILE_CFLAGS@\nSNDFILE_LIBS = @SNDFILE_LIBS@\nSTRIP = @STRIP@\nU = @U@\nVERSION = @VERSION@\nWITH_FRONTEND = @WITH_FRONTEND@\nWITH_MP3RTP = @WITH_MP3RTP@\nWITH_MP3X = @WITH_MP3X@\nabs_builddir = @abs_builddir@\nabs_srcdir = @abs_srcdir@\nabs_top_builddir = @abs_top_builddir@\nabs_top_srcdir = @abs_top_srcdir@\nac_ct_CC = @ac_ct_CC@\nac_ct_DUMPBIN = @ac_ct_DUMPBIN@\nam__include = @am__include@\nam__leading_dot = @am__leading_dot@\nam__quote = @am__quote@\nam__tar = @am__tar@\nam__untar = @am__untar@\nbindir = @bindir@\nbuild = @build@\nbuild_alias = @build_alias@\nbuild_cpu = @build_cpu@\nbuild_os = @build_os@\nbuild_vendor = @build_vendor@\nbuilddir = @builddir@\ndatadir = @datadir@\ndatarootdir = @datarootdir@\ndocdir = @docdir@\ndvidir = @dvidir@\nexec_prefix = @exec_prefix@\nhost = @host@\nhost_alias = @host_alias@\nhost_cpu = @host_cpu@\nhost_os = @host_os@\nhost_vendor = @host_vendor@\nhtmldir = @htmldir@\nincludedir = @includedir@\ninfodir = @infodir@\ninstall_sh = @install_sh@\nlibdir = @libdir@\nlibexecdir = @libexecdir@\nlocaledir = @localedir@\nlocalstatedir = @localstatedir@\nmandir = @mandir@\nmkdir_p = @mkdir_p@\noldincludedir = @oldincludedir@\npdfdir = @pdfdir@\nprefix = @prefix@\nprogram_transform_name = @program_transform_name@\npsdir = @psdir@\nsbindir = @sbindir@\nsharedstatedir = @sharedstatedir@\nsrcdir = @srcdir@\nsysconfdir = @sysconfdir@\ntarget_alias = @target_alias@\ntop_build_prefix = @top_build_prefix@\ntop_builddir = @top_builddir@\ntop_srcdir = @top_srcdir@\nAUTOMAKE_OPTIONS = 1.11 foreign $(top_srcdir)/ansi2knr\n@WITH_XMM_TRUE@noinst_LTLIBRARIES = liblamevectorroutines.la\nxmm_sources = xmm_quantize_sub.c\n@WITH_XMM_TRUE@liblamevectorroutines_la_SOURCES = $(xmm_sources)\nnoinst_HEADERS = lame_intrin.h\nEXTRA_liblamevectorroutines_la_SOURCES = $(xmm_sources)\nCLEANFILES = lclint.txt\nLCLINTFLAGS = \\\n\t+posixlib \\\n\t+showsummary \\\n\t+showalluses \\\n\t+whichlib \\\n\t+forcehints \\\n\t-fixedformalarray \\\n\t+matchanyintegral \\\n\t-Dlint\n\nall: all-am\n\n.SUFFIXES:\n.SUFFIXES: .c .lo .o .obj\n$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(top_srcdir)/Makefile.am.global $(am__configure_deps)\n\t@for dep in $?; do \\\n\t  case '$(am__configure_deps)' in \\\n\t    *$$dep*) \\\n\t      ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \\\n\t        && { if test -f $@; then exit 0; else break; fi; }; \\\n\t      exit 1;; \\\n\t  esac; \\\n\tdone; \\\n\techo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign libmp3lame/vector/Makefile'; \\\n\t$(am__cd) $(top_srcdir) && \\\n\t  $(AUTOMAKE) --foreign libmp3lame/vector/Makefile\n.PRECIOUS: Makefile\nMakefile: $(srcdir)/Makefile.in $(top_builddir)/config.status\n\t@case '$?' in \\\n\t  *config.status*) \\\n\t    cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \\\n\t  *) \\\n\t    echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \\\n\t    cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \\\n\tesac;\n\n$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)\n\tcd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh\n\n$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps)\n\tcd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh\n$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps)\n\tcd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh\n$(am__aclocal_m4_deps):\n\nclean-noinstLTLIBRARIES:\n\t-test -z \"$(noinst_LTLIBRARIES)\" || rm -f $(noinst_LTLIBRARIES)\n\t@list='$(noinst_LTLIBRARIES)'; for p in $$list; do \\\n\t  dir=\"`echo $$p | sed -e 's|/[^/]*$$||'`\"; \\\n\t  test \"$$dir\" != \"$$p\" || dir=.; \\\n\t  echo \"rm -f \\\"$${dir}/so_locations\\\"\"; \\\n\t  rm -f \"$${dir}/so_locations\"; \\\n\tdone\nliblamevectorroutines.la: $(liblamevectorroutines_la_OBJECTS) $(liblamevectorroutines_la_DEPENDENCIES) \n\t$(LINK) $(am_liblamevectorroutines_la_rpath) $(liblamevectorroutines_la_OBJECTS) $(liblamevectorroutines_la_LIBADD) $(LIBS)\n\nmostlyclean-compile:\n\t-rm -f *.$(OBJEXT)\n\ndistclean-compile:\n\t-rm -f *.tab.c\n$(top_srcdir)/ansi2knr:\n\t$(am__cd) $(top_srcdir) && $(MAKE) $(AM_MAKEFLAGS) ./ansi2knr\n\nmostlyclean-kr:\n\t-test \"$U\" = \"\" || rm -f *_.c\n\n@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/xmm_quantize_sub$U.Plo@am__quote@\n\n.c.o:\n@am__fastdepCC_TRUE@\t$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<\n@am__fastdepCC_TRUE@\t$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po\n@AMDEP_TRUE@@am__fastdepCC_FALSE@\tsource='$<' object='$@' libtool=no @AMDEPBACKSLASH@\n@AMDEP_TRUE@@am__fastdepCC_FALSE@\tDEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@\n@am__fastdepCC_FALSE@\t$(COMPILE) -c $<\n\n.c.obj:\n@am__fastdepCC_TRUE@\t$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`\n@am__fastdepCC_TRUE@\t$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po\n@AMDEP_TRUE@@am__fastdepCC_FALSE@\tsource='$<' object='$@' libtool=no @AMDEPBACKSLASH@\n@AMDEP_TRUE@@am__fastdepCC_FALSE@\tDEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@\n@am__fastdepCC_FALSE@\t$(COMPILE) -c `$(CYGPATH_W) '$<'`\n\n.c.lo:\n@am__fastdepCC_TRUE@\t$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<\n@am__fastdepCC_TRUE@\t$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo\n@AMDEP_TRUE@@am__fastdepCC_FALSE@\tsource='$<' object='$@' libtool=yes @AMDEPBACKSLASH@\n@AMDEP_TRUE@@am__fastdepCC_FALSE@\tDEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@\n@am__fastdepCC_FALSE@\t$(LTCOMPILE) -c -o $@ $<\nxmm_quantize_sub_.c: xmm_quantize_sub.c $(ANSI2KNR)\n\t$(CPP) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) `if test -f $(srcdir)/xmm_quantize_sub.c; then echo $(srcdir)/xmm_quantize_sub.c; else echo xmm_quantize_sub.c; fi` | sed 's/^# \\([0-9]\\)/#line \\1/' | $(ANSI2KNR) > $@ || rm -f $@\nxmm_quantize_sub_.$(OBJEXT) xmm_quantize_sub_.lo : $(ANSI2KNR)\n\nmostlyclean-libtool:\n\t-rm -f *.lo\n\nclean-libtool:\n\t-rm -rf .libs _libs\n\nID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)\n\tlist='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \\\n\tunique=`for i in $$list; do \\\n\t    if test -f \"$$i\"; then echo $$i; else echo $(srcdir)/$$i; fi; \\\n\t  done | \\\n\t  $(AWK) '{ files[$$0] = 1; nonempty = 1; } \\\n\t      END { if (nonempty) { for (i in files) print i; }; }'`; \\\n\tmkid -fID $$unique\ntags: TAGS\n\nTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \\\n\t\t$(TAGS_FILES) $(LISP)\n\tset x; \\\n\there=`pwd`; \\\n\tlist='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \\\n\tunique=`for i in $$list; do \\\n\t    if test -f \"$$i\"; then echo $$i; else echo $(srcdir)/$$i; fi; \\\n\t  done | \\\n\t  $(AWK) '{ files[$$0] = 1; nonempty = 1; } \\\n\t      END { if (nonempty) { for (i in files) print i; }; }'`; \\\n\tshift; \\\n\tif test -z \"$(ETAGS_ARGS)$$*$$unique\"; then :; else \\\n\t  test -n \"$$unique\" || unique=$$empty_fix; \\\n\t  if test $$# -gt 0; then \\\n\t    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \\\n\t      \"$$@\" $$unique; \\\n\t  else \\\n\t    $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \\\n\t      $$unique; \\\n\t  fi; \\\n\tfi\nctags: CTAGS\nCTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \\\n\t\t$(TAGS_FILES) $(LISP)\n\tlist='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \\\n\tunique=`for i in $$list; do \\\n\t    if test -f \"$$i\"; then echo $$i; else echo $(srcdir)/$$i; fi; \\\n\t  done | \\\n\t  $(AWK) '{ files[$$0] = 1; nonempty = 1; } \\\n\t      END { if (nonempty) { for (i in files) print i; }; }'`; \\\n\ttest -z \"$(CTAGS_ARGS)$$unique\" \\\n\t  || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \\\n\t     $$unique\n\nGTAGS:\n\there=`$(am__cd) $(top_builddir) && pwd` \\\n\t  && $(am__cd) $(top_srcdir) \\\n\t  && gtags -i $(GTAGS_ARGS) \"$$here\"\n\ndistclean-tags:\n\t-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags\n\ndistdir: $(DISTFILES)\n\t@srcdirstrip=`echo \"$(srcdir)\" | sed 's/[].[^$$\\\\*]/\\\\\\\\&/g'`; \\\n\ttopsrcdirstrip=`echo \"$(top_srcdir)\" | sed 's/[].[^$$\\\\*]/\\\\\\\\&/g'`; \\\n\tlist='$(DISTFILES)'; \\\n\t  dist_files=`for file in $$list; do echo $$file; done | \\\n\t  sed -e \"s|^$$srcdirstrip/||;t\" \\\n\t      -e \"s|^$$topsrcdirstrip/|$(top_builddir)/|;t\"`; \\\n\tcase $$dist_files in \\\n\t  */*) $(MKDIR_P) `echo \"$$dist_files\" | \\\n\t\t\t   sed '/\\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \\\n\t\t\t   sort -u` ;; \\\n\tesac; \\\n\tfor file in $$dist_files; do \\\n\t  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \\\n\t  if test -d $$d/$$file; then \\\n\t    dir=`echo \"/$$file\" | sed -e 's,/[^/]*$$,,'`; \\\n\t    if test -d \"$(distdir)/$$file\"; then \\\n\t      find \"$(distdir)/$$file\" -type d ! -perm -700 -exec chmod u+rwx {} \\;; \\\n\t    fi; \\\n\t    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \\\n\t      cp -fpR $(srcdir)/$$file \"$(distdir)$$dir\" || exit 1; \\\n\t      find \"$(distdir)/$$file\" -type d ! -perm -700 -exec chmod u+rwx {} \\;; \\\n\t    fi; \\\n\t    cp -fpR $$d/$$file \"$(distdir)$$dir\" || exit 1; \\\n\t  else \\\n\t    test -f \"$(distdir)/$$file\" \\\n\t    || cp -p $$d/$$file \"$(distdir)/$$file\" \\\n\t    || exit 1; \\\n\t  fi; \\\n\tdone\ncheck-am: all-am\ncheck: check-am\nall-am: Makefile $(LTLIBRARIES) $(HEADERS)\ninstalldirs:\ninstall: install-am\ninstall-exec: install-exec-am\ninstall-data: install-data-am\nuninstall: uninstall-am\n\ninstall-am: all-am\n\t@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am\n\ninstallcheck: installcheck-am\ninstall-strip:\n\t$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM=\"$(INSTALL_STRIP_PROGRAM)\" \\\n\t  install_sh_PROGRAM=\"$(INSTALL_STRIP_PROGRAM)\" INSTALL_STRIP_FLAG=-s \\\n\t  `test -z '$(STRIP)' || \\\n\t    echo \"INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'\"` install\nmostlyclean-generic:\n\nclean-generic:\n\t-test -z \"$(CLEANFILES)\" || rm -f $(CLEANFILES)\n\ndistclean-generic:\n\t-test -z \"$(CONFIG_CLEAN_FILES)\" || rm -f $(CONFIG_CLEAN_FILES)\n\t-test . = \"$(srcdir)\" || test -z \"$(CONFIG_CLEAN_VPATH_FILES)\" || rm -f $(CONFIG_CLEAN_VPATH_FILES)\n\nmaintainer-clean-generic:\n\t@echo \"This command is intended for maintainers to use\"\n\t@echo \"it deletes files that may require special tools to rebuild.\"\nclean: clean-am\n\nclean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \\\n\tmostlyclean-am\n\ndistclean: distclean-am\n\t-rm -rf ./$(DEPDIR)\n\t-rm -f Makefile\ndistclean-am: clean-am distclean-compile distclean-generic \\\n\tdistclean-tags\n\ndvi: dvi-am\n\ndvi-am:\n\nhtml: html-am\n\nhtml-am:\n\ninfo: info-am\n\ninfo-am:\n\ninstall-data-am:\n\ninstall-dvi: install-dvi-am\n\ninstall-dvi-am:\n\ninstall-exec-am:\n\ninstall-html: install-html-am\n\ninstall-html-am:\n\ninstall-info: install-info-am\n\ninstall-info-am:\n\ninstall-man:\n\ninstall-pdf: install-pdf-am\n\ninstall-pdf-am:\n\ninstall-ps: install-ps-am\n\ninstall-ps-am:\n\ninstallcheck-am:\n\nmaintainer-clean: maintainer-clean-am\n\t-rm -rf ./$(DEPDIR)\n\t-rm -f Makefile\nmaintainer-clean-am: distclean-am maintainer-clean-generic\n\nmostlyclean: mostlyclean-am\n\nmostlyclean-am: mostlyclean-compile mostlyclean-generic mostlyclean-kr \\\n\tmostlyclean-libtool\n\npdf: pdf-am\n\npdf-am:\n\nps: ps-am\n\nps-am:\n\nuninstall-am:\n\n.MAKE: $(top_srcdir)/ansi2knr install-am install-strip\n\n.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \\\n\tclean-libtool clean-noinstLTLIBRARIES ctags distclean \\\n\tdistclean-compile distclean-generic distclean-libtool \\\n\tdistclean-tags distdir dvi dvi-am html html-am info info-am \\\n\tinstall install-am install-data install-data-am install-dvi \\\n\tinstall-dvi-am install-exec install-exec-am install-html \\\n\tinstall-html-am install-info install-info-am install-man \\\n\tinstall-pdf install-pdf-am install-ps install-ps-am \\\n\tinstall-strip installcheck installcheck-am installdirs \\\n\tmaintainer-clean maintainer-clean-generic mostlyclean \\\n\tmostlyclean-compile mostlyclean-generic mostlyclean-kr \\\n\tmostlyclean-libtool pdf pdf-am ps ps-am tags uninstall \\\n\tuninstall-am\n\n\n# end global section\n\nlclint.txt: ${liblamecpuroutines_la_SOURCES} ${noinst_HEADERS}\n\t@lclint ${LCLINTFLAGS} ${INCLUDES} ${DEFS} ${liblamecpuroutines_la_SOURCES} 2>&1 >lclint.txt || true\n\nlclint: lclint.txt\n\tmore lclint.txt\n\n#$(OBJECTS): libtool\n#libtool: $(LIBTOOL_DEPS)\n#\t$(SHELL) $(top_builddir)/config.status --recheck\n\n# Tell versions [3.59,3.63) of GNU make to not export all variables.\n# Otherwise a system limit (for SysV at least) may be exceeded.\n.NOEXPORT:\n"
  },
  {
    "path": "app/jni/libmp3lame/vector/lame_intrin.h",
    "content": "/*\n *      lame_intrin.h include file\n *\n *      Copyright (c) 2006 Gabriel Bouvigne\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n\n#ifndef LAME_INTRIN_H\n#define LAME_INTRIN_H\n\n\nvoid\ninit_xrpow_core_sse(gr_info * const cod_info, FLOAT xrpow[576], int upper, FLOAT * sum);\n\nvoid\nfht_SSE2(FLOAT* , int);\n\n#endif\n"
  },
  {
    "path": "app/jni/libmp3lame/vector/xmm_quantize_sub.c",
    "content": "/*\n * MP3 quantization, intrinsics functions\n *\n *      Copyright (c) 2005-2006 Gabriel Bouvigne\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include \"lame.h\"\n#include \"machine.h\"\n#include \"encoder.h\"\n#include \"util.h\"\n#include \"lame_intrin.h\"\n\n\n\n#ifdef HAVE_XMMINTRIN_H\n\n#include <xmmintrin.h>\n\ntypedef union {\n    int32_t _i_32[4]; /* unions are initialized by its first member */\n    float   _float[4];\n    __m128  _m128;\n} vecfloat_union;\n\n#define TRI_SIZE (5-1)  /* 1024 =  4**5 */\nstatic const FLOAT costab[TRI_SIZE * 2] = {\n    9.238795325112867e-01, 3.826834323650898e-01,\n    9.951847266721969e-01, 9.801714032956060e-02,\n    9.996988186962042e-01, 2.454122852291229e-02,\n    9.999811752826011e-01, 6.135884649154475e-03\n};\n\n\n\nvoid\ninit_xrpow_core_sse(gr_info * const cod_info, FLOAT xrpow[576], int upper, FLOAT * sum)\n{\n    int     i;\n    float   tmp_max = 0;\n    float   tmp_sum = 0;\n    int     upper4 = (upper / 4) * 4;\n    int     rest = upper-upper4;\n\n    const vecfloat_union fabs_mask = {{ 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF }};\n    const __m128 vec_fabs_mask = _mm_loadu_ps(&fabs_mask._float[0]);\n    vecfloat_union vec_xrpow_max;\n    vecfloat_union vec_sum;\n    vecfloat_union vec_tmp;\n\n    _mm_prefetch((char *) cod_info->xr, _MM_HINT_T0);\n    _mm_prefetch((char *) xrpow, _MM_HINT_T0);\n\n    vec_xrpow_max._m128 = _mm_set_ps1(0);\n    vec_sum._m128 = _mm_set_ps1(0);\n\n    for (i = 0; i < upper4; i += 4) {\n        vec_tmp._m128 = _mm_loadu_ps(&(cod_info->xr[i])); /* load */\n        vec_tmp._m128 = _mm_and_ps(vec_tmp._m128, vec_fabs_mask); /* fabs */\n        vec_sum._m128 = _mm_add_ps(vec_sum._m128, vec_tmp._m128);\n        vec_tmp._m128 = _mm_sqrt_ps(_mm_mul_ps(vec_tmp._m128, _mm_sqrt_ps(vec_tmp._m128)));\n        vec_xrpow_max._m128 = _mm_max_ps(vec_xrpow_max._m128, vec_tmp._m128); /* retrieve max */\n        _mm_storeu_ps(&(xrpow[i]), vec_tmp._m128); /* store into xrpow[] */\n    }\n    vec_tmp._m128 = _mm_set_ps1(0);\n    switch (rest) {\n        case 3: vec_tmp._float[2] = cod_info->xr[upper4+2];\n        case 2: vec_tmp._float[1] = cod_info->xr[upper4+1];\n        case 1: vec_tmp._float[0] = cod_info->xr[upper4+0];\n            vec_tmp._m128 = _mm_and_ps(vec_tmp._m128, vec_fabs_mask); /* fabs */\n            vec_sum._m128 = _mm_add_ps(vec_sum._m128, vec_tmp._m128);\n            vec_tmp._m128 = _mm_sqrt_ps(_mm_mul_ps(vec_tmp._m128, _mm_sqrt_ps(vec_tmp._m128)));\n            vec_xrpow_max._m128 = _mm_max_ps(vec_xrpow_max._m128, vec_tmp._m128); /* retrieve max */\n            switch (rest) {\n                case 3: xrpow[upper4+2] = vec_tmp._float[2];\n                case 2: xrpow[upper4+1] = vec_tmp._float[1];\n                case 1: xrpow[upper4+0] = vec_tmp._float[0];\n                default:\n                    break;\n            }\n        default:\n            break;\n    }\n    tmp_sum = vec_sum._float[0] + vec_sum._float[1] + vec_sum._float[2] + vec_sum._float[3];\n    {\n        float ma = vec_xrpow_max._float[0] > vec_xrpow_max._float[1]\n                ? vec_xrpow_max._float[0] : vec_xrpow_max._float[1];\n        float mb = vec_xrpow_max._float[2] > vec_xrpow_max._float[3]\n                ? vec_xrpow_max._float[2] : vec_xrpow_max._float[3];\n        tmp_max = ma > mb ? ma : mb;\n    }\n    cod_info->xrpow_max = tmp_max;\n    *sum = tmp_sum;\n}\n\n\nstatic void store4(__m128 v, float* f0, float* f1, float* f2, float* f3)\n{\n    vecfloat_union r;\n    r._m128 = v;\n    *f0 = r._float[0];\n    *f1 = r._float[1];\n    *f2 = r._float[2];\n    *f3 = r._float[3];\n}\n\n\nvoid\nfht_SSE2(FLOAT * fz, int n)\n{\n    const FLOAT *tri = costab;\n    int     k4;\n    FLOAT  *fi, *gi;\n    FLOAT const *fn;\n\n    n <<= 1;            /* to get BLKSIZE, because of 3DNow! ASM routine */\n    fn = fz + n;\n    k4 = 4;\n    do {\n        FLOAT   s1, c1;\n        int     i, k1, k2, k3, kx;\n        kx = k4 >> 1;\n        k1 = k4;\n        k2 = k4 << 1;\n        k3 = k2 + k1;\n        k4 = k2 << 1;\n        fi = fz;\n        gi = fi + kx;\n        do {\n            FLOAT   f0, f1, f2, f3;\n            f1 = fi[0] - fi[k1];\n            f0 = fi[0] + fi[k1];\n            f3 = fi[k2] - fi[k3];\n            f2 = fi[k2] + fi[k3];\n            fi[k2] = f0 - f2;\n            fi[0] = f0 + f2;\n            fi[k3] = f1 - f3;\n            fi[k1] = f1 + f3;\n            f1 = gi[0] - gi[k1];\n            f0 = gi[0] + gi[k1];\n            f3 = SQRT2 * gi[k3];\n            f2 = SQRT2 * gi[k2];\n            gi[k2] = f0 - f2;\n            gi[0] = f0 + f2;\n            gi[k3] = f1 - f3;\n            gi[k1] = f1 + f3;\n            gi += k4;\n            fi += k4;\n        } while (fi < fn);\n        c1 = tri[0];\n        s1 = tri[1];\n        for (i = 1; i < kx; i++) {\n            __m128 v_s2;\n            __m128 v_c2;\n            __m128 v_c1;\n            __m128 v_s1;\n            FLOAT   c2, s2, s1_2 = s1+s1;\n            c2 = 1 - s1_2 * s1;\n            s2 = s1_2 * c1;\n            fi = fz + i;\n            gi = fz + k1 - i;\n            v_c1 = _mm_set_ps1(c1);\n            v_s1 = _mm_set_ps1(s1);\n            v_c2 = _mm_set_ps1(c2);\n            v_s2 = _mm_set_ps1(s2);\n            {\n                static const vecfloat_union sign_mask = {{0x80000000,0,0,0}};\n                v_c1 = _mm_xor_ps(sign_mask._m128, v_c1); /* v_c1 := {-c1, +c1, +c1, +c1} */\n            }\n            {\n                static const vecfloat_union sign_mask = {{0,0x80000000,0,0}};\n                v_s1 = _mm_xor_ps(sign_mask._m128, v_s1); /* v_s1 := {+s1, -s1, +s1, +s1} */\n            }\n            {\n                static const vecfloat_union sign_mask = {{0,0,0x80000000,0x80000000}};\n                v_c2 = _mm_xor_ps(sign_mask._m128, v_c2); /* v_c2 := {+c2, +c2, -c2, -c2} */\n            }\n            do {\n                __m128 p, q, r;\n\n                q = _mm_setr_ps(fi[k1], fi[k3], gi[k1], gi[k3]); /* Q := {fi_k1,fi_k3,gi_k1,gi_k3}*/\n                p = _mm_mul_ps(_mm_set_ps1(s2), q);              /* P := s2 * Q */\n                q = _mm_mul_ps(v_c2, q);                         /* Q := c2 * Q */\n                q = _mm_shuffle_ps(q, q, _MM_SHUFFLE(1,0,3,2));  /* Q := {-c2*gi_k1,-c2*gi_k3,c2*fi_k1,c2*fi_k3} */\n                p = _mm_add_ps(p, q);\n                \n                r = _mm_setr_ps(gi[0], gi[k2], fi[0], fi[k2]);   /* R := {gi_0,gi_k2,fi_0,fi_k2} */\n                q = _mm_sub_ps(r, p);                            /* Q := {gi_0-p0,gi_k2-p1,fi_0-p2,fi_k2-p3} */\n                r = _mm_add_ps(r, p);                            /* R := {gi_0+p0,gi_k2+p1,fi_0+p2,fi_k2+p3} */\n                p = _mm_shuffle_ps(q, r, _MM_SHUFFLE(2,0,2,0));  /* P := {q0,q2,r0,r2} */\n                p = _mm_shuffle_ps(p, p, _MM_SHUFFLE(3,1,2,0));  /* P := {q0,r0,q2,r2} */\n                q = _mm_shuffle_ps(q, r, _MM_SHUFFLE(3,1,3,1));  /* Q := {q1,q3,r1,r3} */\n                r = _mm_mul_ps(v_c1, q);\n                q = _mm_mul_ps(v_s1, q);\n                q = _mm_shuffle_ps(q, q, _MM_SHUFFLE(0,1,2,3));  /* Q := {q3,q2,q1,q0} */\n                q = _mm_add_ps(q, r);\n\n                store4(_mm_sub_ps(p, q), &gi[k3], &gi[k2], &fi[k3], &fi[k2]);\n                store4(_mm_add_ps(p, q), &gi[k1], &gi[ 0], &fi[k1], &fi[ 0]);\n\n                gi += k4;\n                fi += k4;\n            } while (fi < fn);\n            c2 = c1;\n            c1 = c2 * tri[0] - s1 * tri[1];\n            s1 = c2 * tri[1] + s1 * tri[0];\n        }\n        tri += 2;\n    } while (k4 < n);\n}\n\n#endif\t/* HAVE_XMMINTRIN_H */\n\n"
  },
  {
    "path": "app/jni/libmp3lame/version.c",
    "content": "/*\n *      Version numbering for LAME.\n *\n *      Copyright (c) 1999 A.L. Faber\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n/*!\n  \\file   version.c\n  \\brief  Version numbering for LAME.\n\n  Contains functions which describe the version of LAME.\n\n  \\author A.L. Faber\n  \\version \\$Id: version.c,v 1.32.2.2 2011/11/18 09:18:28 robert Exp $\n  \\ingroup libmp3lame\n*/\n\n\n#ifdef HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n\n#include \"lame.h\"\n#include \"machine.h\"\n\n#include \"version.h\"    /* macros of version numbers */\n\n\n\n\n\n/*! Get the LAME version string. */\n/*!\n  \\param void\n  \\return a pointer to a string which describes the version of LAME.\n*/\nconst char *\nget_lame_version(void)\n{                       /* primary to write screen reports */\n    /* Here we can also add informations about compile time configurations */\n\n#if   LAME_ALPHA_VERSION\n    static /*@observer@ */ const char *const str =\n        STR(LAME_MAJOR_VERSION) \".\" STR(LAME_MINOR_VERSION) \" \"\n        \"(alpha \" STR(LAME_PATCH_VERSION) \", \" __DATE__ \" \" __TIME__ \")\";\n#elif LAME_BETA_VERSION\n    static /*@observer@ */ const char *const str =\n        STR(LAME_MAJOR_VERSION) \".\" STR(LAME_MINOR_VERSION) \" \"\n        \"(beta \" STR(LAME_PATCH_VERSION) \", \" __DATE__ \")\";\n#elif LAME_RELEASE_VERSION && (LAME_PATCH_VERSION > 0)\n    static /*@observer@ */ const char *const str =\n        STR(LAME_MAJOR_VERSION) \".\" STR(LAME_MINOR_VERSION) \".\" STR(LAME_PATCH_VERSION);\n#else\n    static /*@observer@ */ const char *const str =\n        STR(LAME_MAJOR_VERSION) \".\" STR(LAME_MINOR_VERSION);\n#endif\n\n    return str;\n}\n\n\n/*! Get the short LAME version string. */\n/*!\n  It's mainly for inclusion into the MP3 stream.\n\n  \\param void   \n  \\return a pointer to the short version of the LAME version string.\n*/\nconst char *\nget_lame_short_version(void)\n{\n    /* adding date and time to version string makes it harder for output\n       validation */\n\n#if   LAME_ALPHA_VERSION\n    static /*@observer@ */ const char *const str =\n        STR(LAME_MAJOR_VERSION) \".\" STR(LAME_MINOR_VERSION) \" (alpha \" STR(LAME_PATCH_VERSION) \")\";\n#elif LAME_BETA_VERSION\n    static /*@observer@ */ const char *const str =\n        STR(LAME_MAJOR_VERSION) \".\" STR(LAME_MINOR_VERSION) \" (beta \" STR(LAME_PATCH_VERSION) \")\";\n#elif LAME_RELEASE_VERSION && (LAME_PATCH_VERSION > 0)\n    static /*@observer@ */ const char *const str =\n        STR(LAME_MAJOR_VERSION) \".\" STR(LAME_MINOR_VERSION) \".\" STR(LAME_PATCH_VERSION);\n#else\n    static /*@observer@ */ const char *const str =\n        STR(LAME_MAJOR_VERSION) \".\" STR(LAME_MINOR_VERSION);\n#endif\n\n    return str;\n}\n\n/*! Get the _very_ short LAME version string. */\n/*!\n  It's used in the LAME VBR tag only.\n\n  \\param void   \n  \\return a pointer to the short version of the LAME version string.\n*/\nconst char *\nget_lame_very_short_version(void)\n{\n    /* adding date and time to version string makes it harder for output\n       validation */\n#if   LAME_ALPHA_VERSION\n#define P \"a\"\n#elif LAME_BETA_VERSION\n#define P \"b\"\n#elif LAME_RELEASE_VERSION && (LAME_PATCH_VERSION > 0)\n#define P \"r\"\n#else\n#define P \"\"\n#endif\n    static /*@observer@ */ const char *const str =\n#if (LAME_PATCH_VERSION > 0)\n      \"LAME\" STR(LAME_MAJOR_VERSION) \".\" STR(LAME_MINOR_VERSION) P STR(LAME_PATCH_VERSION)\n#else\n      \"LAME\" STR(LAME_MAJOR_VERSION) \".\" STR(LAME_MINOR_VERSION) P\n#endif\n      ;\n    return str;\n}\n\n/*! Get the _very_ short LAME version string. */\n/*!\n  It's used in the LAME VBR tag only, limited to 9 characters max.\n  Due to some 3rd party HW/SW decoders, it has to start with LAME.\n\n  \\param void   \n  \\return a pointer to the short version of the LAME version string.\n */\nconst char*\nget_lame_tag_encoder_short_version(void)\n{\n    static /*@observer@ */ const char *const str =\n            /* FIXME: new scheme / new version counting / drop versioning here ? */\n    \"LAME\" STR(LAME_MAJOR_VERSION) \".\" STR(LAME_MINOR_VERSION) P\n    ;\n    return str;\n}\n\n/*! Get the version string for GPSYCHO. */\n/*!\n  \\param void\n  \\return a pointer to a string which describes the version of GPSYCHO.\n*/\nconst char *\nget_psy_version(void)\n{\n#if   PSY_ALPHA_VERSION > 0\n    static /*@observer@ */ const char *const str =\n        STR(PSY_MAJOR_VERSION) \".\" STR(PSY_MINOR_VERSION)\n        \" (alpha \" STR(PSY_ALPHA_VERSION) \", \" __DATE__ \" \" __TIME__ \")\";\n#elif PSY_BETA_VERSION > 0\n    static /*@observer@ */ const char *const str =\n        STR(PSY_MAJOR_VERSION) \".\" STR(PSY_MINOR_VERSION)\n        \" (beta \" STR(PSY_BETA_VERSION) \", \" __DATE__ \")\";\n#else\n    static /*@observer@ */ const char *const str =\n        STR(PSY_MAJOR_VERSION) \".\" STR(PSY_MINOR_VERSION);\n#endif\n\n    return str;\n}\n\n\n/*! Get the URL for the LAME website. */\n/*!\n  \\param void\n  \\return a pointer to a string which is a URL for the LAME website.\n*/\nconst char *\nget_lame_url(void)\n{\n    static /*@observer@ */ const char *const str = LAME_URL;\n\n    return str;\n}\n\n\n/*! Get the numerical representation of the version. */\n/*!\n  Writes the numerical representation of the version of LAME and\n  GPSYCHO into lvp.\n\n  \\param lvp    \n*/\nvoid\nget_lame_version_numerical(lame_version_t * lvp)\n{\n    static /*@observer@ */ const char *const features = \"\"; /* obsolete */\n\n    /* generic version */\n    lvp->major = LAME_MAJOR_VERSION;\n    lvp->minor = LAME_MINOR_VERSION;\n#if LAME_ALPHA_VERSION\n    lvp->alpha = LAME_PATCH_VERSION;\n    lvp->beta = 0;\n#elif LAME_BETA_VERSION\n    lvp->alpha = 0;\n    lvp->beta = LAME_PATCH_VERSION;\n#else\n    lvp->alpha = 0;\n    lvp->beta = 0;\n#endif\n\n    /* psy version */\n    lvp->psy_major = PSY_MAJOR_VERSION;\n    lvp->psy_minor = PSY_MINOR_VERSION;\n    lvp->psy_alpha = PSY_ALPHA_VERSION;\n    lvp->psy_beta = PSY_BETA_VERSION;\n\n    /* compile time features */\n    /*@-mustfree@ */\n    lvp->features = features;\n    /*@=mustfree@ */\n}\n\n\nconst char *\nget_lame_os_bitness(void)\n{\n    static /*@observer@ */ const char *const strXX = \"\";\n    static /*@observer@ */ const char *const str32 = \"32bits\";\n    static /*@observer@ */ const char *const str64 = \"64bits\";\n\n    switch (sizeof(void *)) {\n    case 4:\n        return str32;\n\n    case 8:\n        return str64;\n\n    default:\n        return strXX;\n    }\n}\n\n/* end of version.c */\n"
  },
  {
    "path": "app/jni/libmp3lame/version.h",
    "content": "/*\n *      Version numbering for LAME.\n *\n *      Copyright (c) 1999 A.L. Faber\n *\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n */\n\n#ifndef LAME_VERSION_H\n#define LAME_VERSION_H\n\n\n/*\n * To make a string from a token, use the # operator:\n */\n#ifndef STR\n# define __STR(x)  #x\n# define STR(x)    __STR(x)\n#endif\n\n# define LAME_URL              \"http://lame.sf.net\"\n\n\n# define LAME_MAJOR_VERSION      3 /* Major version number */\n# define LAME_MINOR_VERSION     99 /* Minor version number */\n# define LAME_TYPE_VERSION       2 /* 0:alpha 1:beta 2:release */\n# define LAME_PATCH_VERSION      5 /* Patch level */\n# define LAME_ALPHA_VERSION     (LAME_TYPE_VERSION==0)\n# define LAME_BETA_VERSION      (LAME_TYPE_VERSION==1)\n# define LAME_RELEASE_VERSION   (LAME_TYPE_VERSION==2)\n\n# define PSY_MAJOR_VERSION       1 /* Major version number */\n# define PSY_MINOR_VERSION       0 /* Minor version number */\n# define PSY_ALPHA_VERSION       0 /* Set number if this is an alpha version, otherwise zero */\n# define PSY_BETA_VERSION        0 /* Set number if this is a beta version, otherwise zero */\n\n#if LAME_ALPHA_VERSION\n#define LAME_PATCH_LEVEL_STRING \" alpha \" STR(LAME_PATCH_VERSION)\n#endif\n#if LAME_BETA_VERSION\n#define LAME_PATCH_LEVEL_STRING \" beta \" STR(LAME_PATCH_VERSION)\n#endif\n#if LAME_RELEASE_VERSION\n#if LAME_PATCH_VERSION\n#define LAME_PATCH_LEVEL_STRING \" release \" STR(LAME_PATCH_VERSION)\n#else\n#define LAME_PATCH_LEVEL_STRING \"\"\n#endif\n#endif\n\n# define LAME_VERSION_STRING STR(LAME_MAJOR_VERSION) \".\" STR(LAME_MINOR_VERSION) LAME_PATCH_LEVEL_STRING\n\n#endif /* LAME_VERSION_H */\n\n/* End of version.h */\n"
  },
  {
    "path": "app/jni/silk.c",
    "content": "//\n// Created by ketian on 16-9-23.\n//\n\n#include \"silk.h\"\n\n#ifdef _WIN32\n#define _CRT_SECURE_NO_DEPRECATE    1\n#endif\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"SKP_Silk_SDK_API.h\"\n#include \"SKP_Silk_SigProc_FIX.h\"\n\n/* Define codec specific settings should be moved to h file */\n#define MAX_BYTES_PER_FRAME     1024\n#define MAX_INPUT_FRAMES        5\n#define MAX_FRAME_LENGTH        480\n#define FRAME_LENGTH_MS         20\n#define MAX_API_FS_KHZ          48\n#define MAX_LBRR_DELAY          2\n\n#ifdef _SYSTEM_IS_BIG_ENDIAN\n/* Function to convert a little endian int16 to a */\n/* big endian int16 or vica verca                 */\nvoid swap_endian(\n    SKP_int16       vec[],\n    SKP_int         len\n)\n{\n    SKP_int i;\n    SKP_int16 tmp;\n    SKP_uint8 *p1, *p2;\n\n    for( i = 0; i < len; i++ ){\n        tmp = vec[ i ];\n        p1 = (SKP_uint8 *)&vec[ i ]; p2 = (SKP_uint8 *)&tmp;\n        p1[ 0 ] = p2[ 1 ]; p1[ 1 ] = p2[ 0 ];\n    }\n}\n#endif\n\n#if (defined(_WIN32) || defined(_WINCE))\n#include <windows.h>\t/* timer */\n#else    // Linux or Mac\n#include <sys/time.h>\n#endif\n\n#ifdef _WIN32\n\nunsigned long GetHighResolutionTime() /* O: time in usec*/\n{\n    /* Returns a time counter in microsec\t*/\n    /* the resolution is platform dependent */\n    /* but is typically 1.62 us resolution  */\n    LARGE_INTEGER lpPerformanceCount;\n    LARGE_INTEGER lpFrequency;\n    QueryPerformanceCounter(&lpPerformanceCount);\n    QueryPerformanceFrequency(&lpFrequency);\n    return (unsigned long)((1000000*(lpPerformanceCount.QuadPart)) / lpFrequency.QuadPart);\n}\n#else    // Linux or Mac\nunsigned long GetHighResolutionTime() /* O: time in usec*/\n{\n    struct timeval tv;\n    gettimeofday(&tv, 0);\n    return((tv.tv_sec*1000000)+(tv.tv_usec));\n}\n#endif // _WIN32\n\n/* Seed for the random number generator, which is used for simulating packet loss */\nstatic SKP_int32 rand_seed = 1;\n\nint convertSilk2PCM(const char* src, const FILE* destFile) {\n    unsigned long tottime, starttime;\n    double    filetime;\n    size_t    counter;\n    SKP_int32 args, totPackets, i, k;\n    SKP_int16 ret, len, tot_len;\n    SKP_int16 nBytes;\n    SKP_uint8 payload[    MAX_BYTES_PER_FRAME * MAX_INPUT_FRAMES * ( MAX_LBRR_DELAY + 1 ) ];\n    SKP_uint8 *payloadEnd = NULL, *payloadToDec = NULL;\n    SKP_uint8 FECpayload[ MAX_BYTES_PER_FRAME * MAX_INPUT_FRAMES ], *payloadPtr;\n    SKP_int16 nBytesFEC;\n    SKP_int16 nBytesPerPacket[ MAX_LBRR_DELAY + 1 ], totBytes;\n    SKP_int16 out[ ( ( FRAME_LENGTH_MS * MAX_API_FS_KHZ ) << 1 ) * MAX_INPUT_FRAMES ], *outPtr;\n    char      bitInFileName[ 150 ];\n    FILE      *bitInFile, *speechOutFile;\n    SKP_int32 packetSize_ms=0, API_Fs_Hz = 0;\n    SKP_int32 decSizeBytes;\n    void      *psDec;\n    SKP_float loss_prob;\n    SKP_int32 frames, lost, quiet;\n    SKP_SILK_SDK_DecControlStruct DecControl;\n\n    strcpy( bitInFileName, src );\n\n    if( !quiet ) {\n        printf(\"********** Silk Decoder (Fixed Point) v %s ********************\\n\", SKP_Silk_SDK_get_version());\n        printf(\"********** Compiled for %d bit cpu *******************************\\n\", (int)sizeof(void*) * 8 );\n        printf( \"Input:                       %s\\n\", bitInFileName );\n    }\n\n    /* Open files */\n    bitInFile = fopen( bitInFileName, \"rb\" );\n    if( bitInFile == NULL ) {\n        printf( \"Error: could not open input file %s\\n\", bitInFileName );\n        exit( 0 );\n    }\n\n    /* Check Silk header */\n    {\n        char header_buf[50];\n        fseek(bitInFile, 1, SEEK_SET);\n        counter = fread(header_buf, sizeof(char), strlen(\"#!SILK_V3\"), bitInFile);\n        header_buf[strlen(\"#!SILK_V3\")] = '\\0'; /* Terminate with a null character */\n        if (strcmp(header_buf, \"#!SILK_V3\") == 0) {\n\n        } else {\n            fseek(bitInFile, 0, SEEK_SET);\n            counter = fread(header_buf, sizeof(char), strlen(\"#!SILK_V3\"), bitInFile);\n            header_buf[strlen(\"#!SILK_V3\")] = '\\0'; /* Terminate with a null character */\n            if (strcmp(header_buf, \"#!SILK_V3\") != 0) {\n                /* Non-equal strings */\n                exit(0);\n            }\n        }\n    }\n\n    speechOutFile = (FILE *) destFile;\n    if( speechOutFile == NULL ) {\n        exit( 0 );\n    }\n\n    /* Set the samplingrate that is requested for the output */\n    DecControl.API_sampleRate = 24000;\n\n    /* Initialize to one frame per packet, for proper concealment before first packet arrives */\n    DecControl.framesPerPacket = 1;\n\n    /* Create decoder */\n    ret = (short) SKP_Silk_SDK_Get_Decoder_Size(&decSizeBytes );\n    if( ret ) {\n        printf( \"\\nSKP_Silk_SDK_Get_Decoder_Size returned %d\", ret );\n    }\n    psDec = malloc((size_t) decSizeBytes);\n\n    /* Reset decoder */\n    ret = (short) SKP_Silk_SDK_InitDecoder(psDec );\n    if( ret ) {\n        printf( \"\\nSKP_Silk_InitDecoder returned %d\", ret );\n    }\n\n    totPackets = 0;\n    tottime    = 0;\n    payloadEnd = payload;\n\n    /* Simulate the jitter buffer holding MAX_FEC_DELAY packets */\n    for( i = 0; i < MAX_LBRR_DELAY; i++ ) {\n        /* Read payload size */\n        counter = fread( &nBytes, sizeof( SKP_int16 ), 1, bitInFile );\n#ifdef _SYSTEM_IS_BIG_ENDIAN\n        swap_endian( &nBytes, 1 );\n#endif\n        /* Read payload */\n        counter = fread( payloadEnd, sizeof( SKP_uint8 ), nBytes, bitInFile );\n\n        if( ( SKP_int16 )counter < nBytes ) {\n            break;\n        }\n        nBytesPerPacket[ i ] = nBytes;\n        payloadEnd          += nBytes;\n        totPackets++;\n    }\n\n    while( 1 ) {\n        /* Read payload size */\n        counter = fread( &nBytes, sizeof( SKP_int16 ), 1, bitInFile );\n#ifdef _SYSTEM_IS_BIG_ENDIAN\n        swap_endian( &nBytes, 1 );\n#endif\n        if( nBytes < 0 || counter < 1 ) {\n            break;\n        }\n\n        /* Read payload */\n        counter = fread( payloadEnd, sizeof( SKP_uint8 ), nBytes, bitInFile );\n        if( ( SKP_int16 )counter < nBytes ) {\n            break;\n        }\n\n        /* Simulate losses */\n        rand_seed = SKP_RAND( rand_seed );\n        if( ( ( ( float )( ( rand_seed >> 16 ) + ( 1 << 15 ) ) ) / 65535.0f >= ( loss_prob / 100.0f ) ) && ( counter > 0 ) ) {\n            nBytesPerPacket[ MAX_LBRR_DELAY ] = nBytes;\n            payloadEnd                       += nBytes;\n        } else {\n            nBytesPerPacket[ MAX_LBRR_DELAY ] = 0;\n        }\n\n        if( nBytesPerPacket[ 0 ] == 0 ) {\n            /* Indicate lost packet */\n            lost = 1;\n\n            /* Packet loss. Search after FEC in next packets. Should be done in the jitter buffer */\n            payloadPtr = payload;\n            for( i = 0; i < MAX_LBRR_DELAY; i++ ) {\n                if( nBytesPerPacket[ i + 1 ] > 0 ) {\n                    starttime = GetHighResolutionTime();\n                    SKP_Silk_SDK_search_for_LBRR( payloadPtr, nBytesPerPacket[ i + 1 ], ( i + 1 ), FECpayload, &nBytesFEC );\n                    tottime += GetHighResolutionTime() - starttime;\n                    if( nBytesFEC > 0 ) {\n                        payloadToDec = FECpayload;\n                        nBytes = nBytesFEC;\n                        lost = 0;\n                        break;\n                    }\n                }\n                payloadPtr += nBytesPerPacket[ i + 1 ];\n            }\n        } else {\n            lost = 0;\n            nBytes = nBytesPerPacket[ 0 ];\n            payloadToDec = payload;\n        }\n\n        /* Silk decoder */\n        outPtr = out;\n        tot_len = 0;\n        starttime = GetHighResolutionTime();\n\n        if( lost == 0 ) {\n            /* No Loss: Decode all frames in the packet */\n            frames = 0;\n            do {\n                /* Decode 20 ms */\n                ret = SKP_Silk_SDK_Decode( psDec, &DecControl, 0, payloadToDec, nBytes, outPtr, &len );\n                if( ret ) {\n                    printf( \"\\nSKP_Silk_SDK_Decode returned %d\", ret );\n                }\n\n                frames++;\n                outPtr  += len;\n                tot_len += len;\n                if( frames > MAX_INPUT_FRAMES ) {\n                    /* Hack for corrupt stream that could generate too many frames */\n                    outPtr  = out;\n                    tot_len = 0;\n                    frames  = 0;\n                }\n                /* Until last 20 ms frame of packet has been decoded */\n            } while( DecControl.moreInternalDecoderFrames );\n        } else {\n            /* Loss: Decode enough frames to cover one packet duration */\n            for( i = 0; i < DecControl.framesPerPacket; i++ ) {\n                /* Generate 20 ms */\n                ret = SKP_Silk_SDK_Decode( psDec, &DecControl, 1, payloadToDec, nBytes, outPtr, &len );\n                if( ret ) {\n                    printf( \"\\nSKP_Silk_Decode returned %d\", ret );\n                }\n                outPtr  += len;\n                tot_len += len;\n            }\n        }\n\n        packetSize_ms = tot_len / ( DecControl.API_sampleRate / 1000 );\n        tottime += GetHighResolutionTime() - starttime;\n        totPackets++;\n\n        /* Write output to file */\n#ifdef _SYSTEM_IS_BIG_ENDIAN\n        swap_endian( out, tot_len );\n#endif\n        fwrite( out, sizeof( SKP_int16 ), tot_len, speechOutFile );\n\n        /* Update buffer */\n        totBytes = 0;\n        for( i = 0; i < MAX_LBRR_DELAY; i++ ) {\n            totBytes += nBytesPerPacket[ i + 1 ];\n        }\n        SKP_memmove( payload, &payload[ nBytesPerPacket[ 0 ] ], totBytes * sizeof( SKP_uint8 ) );\n        payloadEnd -= nBytesPerPacket[ 0 ];\n        SKP_memmove( nBytesPerPacket, &nBytesPerPacket[ 1 ], MAX_LBRR_DELAY * sizeof( SKP_int16 ) );\n    }\n\n    /* Empty the recieve buffer */\n    for( k = 0; k < MAX_LBRR_DELAY; k++ ) {\n        if( nBytesPerPacket[ 0 ] == 0 ) {\n            /* Indicate lost packet */\n            lost = 1;\n\n            /* Packet loss. Search after FEC in next packets. Should be done in the jitter buffer */\n            payloadPtr = payload;\n            for( i = 0; i < MAX_LBRR_DELAY; i++ ) {\n                if( nBytesPerPacket[ i + 1 ] > 0 ) {\n                    starttime = GetHighResolutionTime();\n                    SKP_Silk_SDK_search_for_LBRR( payloadPtr, nBytesPerPacket[ i + 1 ], ( i + 1 ), FECpayload, &nBytesFEC );\n                    tottime += GetHighResolutionTime() - starttime;\n                    if( nBytesFEC > 0 ) {\n                        payloadToDec = FECpayload;\n                        nBytes = nBytesFEC;\n                        lost = 0;\n                        break;\n                    }\n                }\n                payloadPtr += nBytesPerPacket[ i + 1 ];\n            }\n        } else {\n            lost = 0;\n            nBytes = nBytesPerPacket[ 0 ];\n            payloadToDec = payload;\n        }\n\n        /* Silk decoder */\n        outPtr  = out;\n        tot_len = 0;\n        starttime = GetHighResolutionTime();\n\n        if( lost == 0 ) {\n            /* No loss: Decode all frames in the packet */\n            frames = 0;\n            do {\n                /* Decode 20 ms */\n                ret = SKP_Silk_SDK_Decode( psDec, &DecControl, 0, payloadToDec, nBytes, outPtr, &len );\n                if( ret ) {\n                    printf( \"\\nSKP_Silk_SDK_Decode returned %d\", ret );\n                }\n\n                frames++;\n                outPtr  += len;\n                tot_len += len;\n                if( frames > MAX_INPUT_FRAMES ) {\n                    /* Hack for corrupt stream that could generate too many frames */\n                    outPtr  = out;\n                    tot_len = 0;\n                    frames  = 0;\n                }\n                /* Until last 20 ms frame of packet has been decoded */\n            } while( DecControl.moreInternalDecoderFrames );\n        } else {\n            /* Loss: Decode enough frames to cover one packet duration */\n\n            /* Generate 20 ms */\n            for( i = 0; i < DecControl.framesPerPacket; i++ ) {\n                ret = SKP_Silk_SDK_Decode( psDec, &DecControl, 1, payloadToDec, nBytes, outPtr, &len );\n                if( ret ) {\n                    printf( \"\\nSKP_Silk_Decode returned %d\", ret );\n                }\n                outPtr  += len;\n                tot_len += len;\n            }\n        }\n\n        packetSize_ms = tot_len / ( DecControl.API_sampleRate / 1000 );\n        tottime += GetHighResolutionTime() - starttime;\n        totPackets++;\n\n        /* Write output to file */\n#ifdef _SYSTEM_IS_BIG_ENDIAN\n        swap_endian( out, tot_len );\n#endif\n        fwrite( out, sizeof( SKP_int16 ), tot_len, speechOutFile );\n\n        /* Update Buffer */\n        totBytes = 0;\n        for( i = 0; i < MAX_LBRR_DELAY; i++ ) {\n            totBytes += nBytesPerPacket[ i + 1 ];\n        }\n        SKP_memmove( payload, &payload[ nBytesPerPacket[ 0 ] ], totBytes * sizeof( SKP_uint8 ) );\n        payloadEnd -= nBytesPerPacket[ 0 ];\n        SKP_memmove( nBytesPerPacket, &nBytesPerPacket[ 1 ], MAX_LBRR_DELAY * sizeof( SKP_int16 ) );\n    }\n\n    /* Free decoder */\n    free( psDec );\n\n    /* Close files */\n    fclose( bitInFile );\n\n    filetime = totPackets * 1e-3 * packetSize_ms;\n    if( !quiet ) {\n        printf(\"\\nFile length:                 %.3f s\", filetime);\n        printf(\"\\nTime for decoding:           %.3f s (%.3f%% of realtime)\", 1e-6 * tottime, 1e-4 * tottime / filetime);\n        printf(\"\\n\\n\");\n    } else {\n        /* print time and % of realtime */\n        printf( \"%.3f %.3f %d\\n\", 1e-6 * tottime, 1e-4 * tottime / filetime, totPackets );\n    }\n    return 0;\n}"
  },
  {
    "path": "app/proguard-rules.pro",
    "content": "# Add project specific ProGuard rules here.\n# By default, the flags in this file are appended to flags specified\n# in /home/ketian/tools/adt-bundle-linux-x86_64-20140702/sdk/tools/proguard/proguard-android.txt\n# You can edit the include path and order by changing the proguardFiles\n# directive in build.gradle.\n#\n# For more details, see\n#   http://developer.android.com/guide/developing/tools/proguard.html\n\n# Add any project specific keep options here:\n\n# If your project uses WebView with JS, uncomment the following\n# and specify the fully qualified class name to the JavaScript interface\n# class:\n#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\n#   public *;\n#}\n"
  },
  {
    "path": "app/src/main/AndroidManifest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    package=\"com.ketian.android.silkv3\">\n\n    <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />\n    <uses-permission android:name=\"android.permission.READ_EXTERNAL_STORAGE\" />\n\n    <application\n        android:name=\".App\"\n        android:allowBackup=\"true\"\n        android:icon=\"@mipmap/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:supportsRtl=\"true\"\n        android:theme=\"@style/AppTheme\">\n        <activity android:name=\".MainActivity\">\n            <intent-filter>\n                <action android:name=\"android.intent.action.MAIN\" />\n\n                <category android:name=\"android.intent.category.LAUNCHER\" />\n            </intent-filter>\n        </activity>\n    </application>\n\n</manifest>"
  },
  {
    "path": "app/src/main/java/com/ketian/android/silkv3/App.kt",
    "content": "package com.ketian.android.silkv3\n\nimport android.app.Application\n\n/**\n * Created by ketian.\n */\nclass App : Application() {\n\n    override fun onCreate() {\n        super.onCreate()\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/com/ketian/android/silkv3/ExportFragment.kt",
    "content": "package com.ketian.android.silkv3\n\nimport android.os.Bundle\nimport androidx.fragment.app.Fragment\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\n\n/**\n * Created by ketian.\n */\n\nclass ExportFragment : Fragment() {\n\n    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {\n        return inflater.inflate(R.layout.fragment_export, container, false)\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/com/ketian/android/silkv3/MainActivity.kt",
    "content": "package com.ketian.android.silkv3\n\nimport android.Manifest\nimport android.content.pm.PackageManager\nimport android.os.Bundle\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.core.app.ActivityCompat\nimport androidx.core.content.ContextCompat\nimport androidx.fragment.app.Fragment\nimport androidx.fragment.app.FragmentManager\nimport androidx.fragment.app.FragmentPagerAdapter\nimport kotlinx.android.synthetic.main.activity_main.*\nimport java.util.*\n\nclass MainActivity : AppCompatActivity() {\n    private var mPagerAdapter: PagerAdapter? = null\n    private var mFragments: MutableList<Fragment>? = null\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n        setContentView(R.layout.activity_main)\n        hint.text=\"\"\n        if (getPermission()) {\n            initFragments()\n            mPagerAdapter = PagerAdapter(supportFragmentManager)\n            pager.adapter = mPagerAdapter\n        }\n    }\n\n    fun getPermission(): Boolean {\n        val permissionCheck1 = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);\n        val permissionCheck2 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);\n        if (permissionCheck1 != PackageManager.PERMISSION_GRANTED || permissionCheck2 != PackageManager.PERMISSION_GRANTED) {\n            ActivityCompat.requestPermissions(this,\n                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE),\n                    124)\n            return false\n        }\n        return true\n    }\n\n    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {\n        super.onRequestPermissionsResult(requestCode, permissions, grantResults)\n        if (requestCode == 124) {\n            if ((grantResults.isNotEmpty()) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {\n                initFragments()\n                mPagerAdapter = PagerAdapter(supportFragmentManager)\n                pager.adapter = mPagerAdapter\n            }\n        }\n    }\n\n    private fun initFragments() {\n        mFragments = ArrayList(2)\n        mFragments?.add(VoiceFragment())\n        mFragments?.add(ExportFragment())\n    }\n\n    fun wechatVoiceDecodeResult(rlt: Int, dest: String) {\n        when(rlt){\n            0->{\n                hint.text=\"参数有误\"\n                Toast.makeText(this, \"参数有误\", Toast.LENGTH_SHORT).show()\n            }\n            1->{\n                hint.text=\"转换成功,恭喜你成功扒了微信的底裤\"\n                Toast.makeText(this, \"Convert to $dest OK\", Toast.LENGTH_SHORT).show()\n            }\n            else->{}\n        }\n    }\n\n    private inner class PagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {\n\n        override fun getItem(position: Int): Fragment? {\n            return mFragments?.get(position)\n        }\n\n        override fun getCount(): Int {\n            return mFragments?.size ?: 0\n        }\n    }\n\n\n}\n"
  },
  {
    "path": "app/src/main/java/com/ketian/android/silkv3/PathUtils.kt",
    "content": "package com.ketian.android.silkv3\n\nimport android.content.Context\nimport android.os.Environment\nimport android.util.Log\nimport java.io.File\nimport java.util.*\n\n/**\n * Created by ketian.\n */\nclass PathUtils private constructor(context: Context) {\n    var exportDir: String? = null\n        private set\n    var voice_wechat_paths: MutableList<String>\n    var voice_qq_paths: List<String>\n\n    init {\n        context.toString()\n        voice_wechat_paths = ArrayList()\n        voice_qq_paths = ArrayList()\n        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {\n            Log.e(\"doInBackground\",\"哪个快?\")\n            val dir = Environment.getExternalStorageDirectory()\n            val f = File(\"${dir.path}/tencent/MicroMsg/\")\n            var interrupt = false\n            if (f.exists() &&  f.isDirectory) {\n                val files = f.listFiles()\n                if (files != null && files.isNotEmpty()) {\n                    for (f0 in files) {\n                        if (f0.isDirectory && f0.name.length > 24) {\n                            voice_wechat_paths.add(f0.absolutePath + \"/voice2\")\n                        }\n                    }\n                } else {\n                    interrupt = true\n                }\n            }\n            if (!interrupt) {\n                val exportDir = File(dir, \"silkv3_mp3\")\n                if (!exportDir.exists()) {\n                    exportDir.mkdirs()\n                }\n                this.exportDir = exportDir.absolutePath\n            }\n        }\n    }\n\n    companion object {\n        private var instance: PathUtils? = null\n\n        private fun createUtil(context: Context): PathUtils {\n            if (instance == null) {\n                instance = PathUtils(context)\n            }\n            return instance!!\n        }\n\n        fun getVoiceFiles_WeChat(context: Context): List<String> {\n            return createUtil(context).voice_wechat_paths\n        }\n\n        fun getVoiceFiles_QQ(context: Context): List<String> {\n            return createUtil(context).voice_qq_paths\n        }\n\n        fun getExportDir(context: Context): String? {\n            return createUtil(context).exportDir\n        }\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/com/ketian/android/silkv3/VoiceFragment.kt",
    "content": "package com.ketian.android.silkv3\n\nimport android.content.Context\nimport android.os.AsyncTask\nimport android.os.Bundle\nimport android.util.Log\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport android.widget.Button\nimport android.widget.TextView\nimport androidx.fragment.app.Fragment\nimport androidx.recyclerview.widget.LinearLayoutManager\nimport androidx.recyclerview.widget.RecyclerView\nimport com.ketian.android.silkv3.jni.JNI\nimport kotlinx.android.synthetic.main.fragment_voice.*\nimport java.io.File\nimport java.util.*\n\n/**\n * Created by ketian.\n */\nclass VoiceFragment : Fragment() {\n\n    private var mTask: LoadTask? = null\n    private var mAdapter: ItemAdapter? = null\n    private val mItems = ArrayList<String>()\n    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {\n        return inflater.inflate(R.layout.fragment_voice, container, false)\n    }\n\n    override fun onActivityCreated(savedInstanceState: Bundle?) {\n        super.onActivityCreated(savedInstanceState)\n        recycler_view.apply {\n            layoutManager = LinearLayoutManager(this.context)\n            adapter = ItemAdapter(requireContext(), mItems).apply {\n                mAdapter = this\n            }\n            initData()\n        }\n    }\n\n    private fun initData() {\n        mTask?.cancel(true)\n        mTask = LoadTask(requireContext())\n        mTask?.execute()\n    }\n\n    private inner class LoadTask(private val mContext: Context) : AsyncTask<Void, Void, List<String>>() {\n\n        override fun onPreExecute() {\n\n        }\n\n        override fun doInBackground(vararg voids: Void): List<String> {\n            val paths = PathUtils.getVoiceFiles_WeChat(mContext)\n            Log.e(\"doInBackground\", \"${paths}\")\n            val voicePaths = ArrayList<String>()\n\n            if (paths.size > 0) {\n                var file: File?\n                for (path in paths) {\n                    file = File(path)\n                    if (file.exists() && file.isDirectory) {\n                        val stack = Stack<String>()\n                        stack.push(path)\n                        while (!stack.empty()) {\n                            var fs: Array<File>? = null\n                            val parent = stack.pop()\n                            if (parent != null) {\n                                file = File(parent)\n                                if (file.isDirectory) { // ignore file, FIXME\n                                    fs = file.listFiles()\n                                } else {\n                                    continue\n                                }\n                            }\n                            if (fs == null || fs.isEmpty()) continue\n                            for (i in fs.indices) {\n                                val name = fs[i].name\n                                if (fs[i].isDirectory && name != \".\"\n                                        && name != \"..\") {\n                                    stack.push(fs[i].path)\n                                } else if (fs[i].isFile) {\n                                    if (name.endsWith(\".amr\")) {\n                                        voicePaths.add(fs[i].absolutePath)\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n            return voicePaths\n        }\n\n        override fun onPostExecute(strings: List<String>) {\n            mItems.clear()\n            mItems.addAll(strings)\n            mAdapter?.notifyDataSetChanged()\n        }\n    }\n\n    override fun onDestroy() {\n        super.onDestroy()\n        if (mTask != null) {\n            mTask!!.cancel(true)\n        }\n    }\n\n    private class ItemAdapter(private val mContext: Context, private val paths: List<String>?) : RecyclerView.Adapter<ItemAdapter.VH>() {\n\n        private val listener = View.OnClickListener { view ->\n            val index = view.tag as Int\n            val path = paths?.get(index) ?: return@OnClickListener\n            val file = File(path)\n            if (file.exists() && file.canRead()) {\n                val dest = PathUtils.getExportDir(mContext) + \"/\" + file.name + \".mp3\"\n                val temp = PathUtils.getExportDir(mContext) + \"/temp_\" + file.name + \".mp3\"\n                val rlt = JNI.convert(path, dest, temp)\n                (mContext as? MainActivity)?.wechatVoiceDecodeResult(rlt,dest)\n            }\n        }\n\n        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemAdapter.VH {\n            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)\n            return VH(view)\n        }\n\n        override fun onBindViewHolder(holder: ItemAdapter.VH, position: Int) {\n            holder.textView.text = paths!![position]\n            holder.button.tag = position\n            holder.button.setOnClickListener(listener)\n        }\n\n        override fun getItemCount(): Int {\n            return paths?.size ?: 0\n        }\n\n        class VH(itemView: View) : RecyclerView.ViewHolder(itemView) {\n            var textView: TextView\n            var button: Button\n\n            init {\n                textView = itemView.findViewById<View>(R.id.title) as TextView\n                button = itemView.findViewById<View>(R.id.click) as Button\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "app/src/main/java/com/ketian/android/silkv3/jni/JNI.kt",
    "content": "package com.ketian.android.silkv3.jni\n\n/**\n * Created by ketian on 16-10-10.\n */\n\nobject JNI {\n\n    init {\n        System.loadLibrary(\"silkx\")\n    }\n\n    external fun convert(src: String, dest: String, tmpfile: String): Int\n\n}\n"
  },
  {
    "path": "app/src/main/res/layout/activity_main.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    tools:context=\"com.ketian.android.silkv3.MainActivity\">\n\n    <androidx.viewpager.widget.ViewPager\n        android:id=\"@+id/pager\"\n        android:layout_width=\"0dp\"\n        android:layout_height=\"0dp\"\n        app:layout_constraintBottom_toBottomOf=\"parent\"\n        app:layout_constraintLeft_toLeftOf=\"parent\"\n        app:layout_constraintRight_toRightOf=\"parent\"\n        app:layout_constraintTop_toTopOf=\"parent\" />\n\n    <TextView\n        android:id=\"@+id/hint\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        app:layout_constrainedWidth=\"true\"\n        app:layout_constrainedHeight=\"true\"\n        android:gravity=\"center\"\n        android:text=\"@string/fuck_google\"\n        android:textSize=\"20sp\"\n        app:layout_constraintBottom_toBottomOf=\"parent\"\n        app:layout_constraintLeft_toLeftOf=\"parent\"\n        app:layout_constraintRight_toRightOf=\"parent\"\n        app:layout_constraintTop_toTopOf=\"parent\" />\n\n</androidx.constraintlayout.widget.ConstraintLayout>\n"
  },
  {
    "path": "app/src/main/res/layout/export_item_layout.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<TextView xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:id=\"@+id/title\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\" />"
  },
  {
    "path": "app/src/main/res/layout/fragment_export.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\">\n\n    <androidx.recyclerview.widget.RecyclerView\n        android:id=\"@+id/recycler_view\"\n        android:layout_width=\"0dp\"\n        android:layout_height=\"0dp\"\n        android:background=\"@color/colorPrimary\"\n        app:layout_constraintBottom_toBottomOf=\"parent\"\n        app:layout_constraintLeft_toLeftOf=\"parent\"\n        app:layout_constraintRight_toRightOf=\"parent\"\n        app:layout_constraintTop_toTopOf=\"parent\"\n        tools:listitem=\"@layout/item_layout\" />\n\n</androidx.constraintlayout.widget.ConstraintLayout>"
  },
  {
    "path": "app/src/main/res/layout/fragment_voice.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\">\n\n    <androidx.recyclerview.widget.RecyclerView\n        android:id=\"@+id/recycler_view\"\n        android:layout_width=\"0dp\"\n        android:layout_height=\"0dp\"\n        android:background=\"@color/colorAccent\"\n        app:layout_constraintBottom_toBottomOf=\"parent\"\n        app:layout_constraintLeft_toLeftOf=\"parent\"\n        app:layout_constraintRight_toRightOf=\"parent\"\n        app:layout_constraintTop_toTopOf=\"parent\"\n        tools:listitem=\"@layout/item_layout\" />\n\n</androidx.constraintlayout.widget.ConstraintLayout>"
  },
  {
    "path": "app/src/main/res/layout/item_layout.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"wrap_content\"\n    android:orientation=\"horizontal\">\n\n    <TextView\n        android:id=\"@+id/title\"\n        android:layout_width=\"0dp\"\n        android:layout_height=\"wrap_content\"\n        android:layout_weight=\"1\" />\n\n    <Button\n        android:id=\"@+id/click\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_gravity=\"center_vertical\"\n        android:text=\"Convert\" />\n\n</LinearLayout>"
  },
  {
    "path": "app/src/main/res/values/colors.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <color name=\"colorPrimary\">#3F51B5</color>\n    <color name=\"colorPrimaryDark\">#303F9F</color>\n    <color name=\"colorAccent\">#FF4081</color>\n</resources>\n"
  },
  {
    "path": "app/src/main/res/values/dimens.xml",
    "content": "<resources>\n    <!-- Default screen margins, per the Android Design guidelines. -->\n    <dimen name=\"activity_horizontal_margin\">16dp</dimen>\n    <dimen name=\"activity_vertical_margin\">16dp</dimen>\n</resources>\n"
  },
  {
    "path": "app/src/main/res/values/strings.xml",
    "content": "<resources>\n    <string name=\"app_name\">AndroidSilkV3</string>\n    <string name=\"fuck_google\">Tips:模拟器报android.view.View$OnUnhandledKeyEventListener不用管它,页面没问题的</string>\n</resources>\n"
  },
  {
    "path": "app/src/main/res/values/styles.xml",
    "content": "<resources>\n\n    <!-- Base application theme. -->\n    <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\">\n        <!-- Customize your theme here. -->\n        <item name=\"colorPrimary\">@color/colorPrimary</item>\n        <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item>\n        <item name=\"colorAccent\">@color/colorAccent</item>\n    </style>\n\n</resources>\n"
  },
  {
    "path": "app/src/main/res/values-w820dp/dimens.xml",
    "content": "<resources>\n    <!-- Example customization of dimensions originally defined in res/values/dimens.xml\n         (such as screen margins) for screens with more than 820dp of available width. This\n         would include 7\" and 10\" devices in landscape (~960dp and ~1280dp respectively). -->\n    <dimen name=\"activity_horizontal_margin\">64dp</dimen>\n</resources>\n"
  },
  {
    "path": "build.gradle",
    "content": "// Top-level build file where you can add configuration options common to all sub-projects/modules.\n\nbuildscript {\n    ext.kotlin_version = '1.3.31'\n    repositories {\n        jcenter()\n        google()\n    }\n    dependencies {\n        classpath 'com.android.tools.build:gradle:3.4.0'\n        classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n\n        // NOTE: Do not place your application dependencies here; they belong\n        // in the individual module build.gradle files\n    }\n}\n\nallprojects {\n    repositories {\n        jcenter()\n        google()\n    }\n}\n\ntask clean(type: Delete) {\n    delete rootProject.buildDir\n}\n"
  },
  {
    "path": "gradle/wrapper/gradle-wrapper.properties",
    "content": "#Wed Apr 24 16:10:40 CST 2019\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-5.1.1-all.zip\n"
  },
  {
    "path": "gradle.properties",
    "content": "# Project-wide Gradle settings.\n\n# IDE (e.g. Android Studio) users:\n# Gradle settings configured through the IDE *will override*\n# any settings specified in this file.\n\n# For more details on how to configure your build environment visit\n# http://www.gradle.org/docs/current/userguide/build_environment.html\n\n# Specifies the JVM arguments used for the daemon process.\n# The setting is particularly useful for tweaking memory settings.\n# Default value: -Xmx10248m -XX:MaxPermSize=256m\n# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8\n\n# When configured, Gradle will run in incubating parallel mode.\n# This option should only be used with decoupled projects. More details, visit\n# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects\n# org.gradle.parallel=true\nandroid.enableJetifier=true\nandroid.useAndroidX=true"
  },
  {
    "path": "gradlew",
    "content": "#!/usr/bin/env bash\n\n##############################################################################\n##\n##  Gradle start up script for UN*X\n##\n##############################################################################\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS=\"\"\n\nAPP_NAME=\"Gradle\"\nAPP_BASE_NAME=`basename \"$0\"`\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=\"maximum\"\n\nwarn ( ) {\n    echo \"$*\"\n}\n\ndie ( ) {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n}\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\ncase \"`uname`\" in\n  CYGWIN* )\n    cygwin=true\n    ;;\n  Darwin* )\n    darwin=true\n    ;;\n  MINGW* )\n    msys=true\n    ;;\nesac\n\n# Attempt to set APP_HOME\n# Resolve links: $0 may be a link\nPRG=\"$0\"\n# Need this for relative symlinks.\nwhile [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n        PRG=\"$link\"\n    else\n        PRG=`dirname \"$PRG\"`\"/$link\"\n    fi\ndone\nSAVED=\"`pwd`\"\ncd \"`dirname \\\"$PRG\\\"`/\" >/dev/null\nAPP_HOME=\"`pwd -P`\"\ncd \"$SAVED\" >/dev/null\n\nCLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n        JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=\"java\"\n    which java >/dev/null 2>&1 || die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\nfi\n\n# Increase the maximum file descriptors if we can.\nif [ \"$cygwin\" = \"false\" -a \"$darwin\" = \"false\" ] ; then\n    MAX_FD_LIMIT=`ulimit -H -n`\n    if [ $? -eq 0 ] ; then\n        if [ \"$MAX_FD\" = \"maximum\" -o \"$MAX_FD\" = \"max\" ] ; then\n            MAX_FD=\"$MAX_FD_LIMIT\"\n        fi\n        ulimit -n $MAX_FD\n        if [ $? -ne 0 ] ; then\n            warn \"Could not set maximum file descriptor limit: $MAX_FD\"\n        fi\n    else\n        warn \"Could not query maximum file descriptor limit: $MAX_FD_LIMIT\"\n    fi\nfi\n\n# For Darwin, add options to specify how the application appears in the dock\nif $darwin; then\n    GRADLE_OPTS=\"$GRADLE_OPTS \\\"-Xdock:name=$APP_NAME\\\" \\\"-Xdock:icon=$APP_HOME/media/gradle.icns\\\"\"\nfi\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin ; then\n    APP_HOME=`cygpath --path --mixed \"$APP_HOME\"`\n    CLASSPATH=`cygpath --path --mixed \"$CLASSPATH\"`\n    JAVACMD=`cygpath --unix \"$JAVACMD\"`\n\n    # We build the pattern for arguments to be converted via cygpath\n    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\n    SEP=\"\"\n    for dir in $ROOTDIRSRAW ; do\n        ROOTDIRS=\"$ROOTDIRS$SEP$dir\"\n        SEP=\"|\"\n    done\n    OURCYGPATTERN=\"(^($ROOTDIRS))\"\n    # Add a user-defined pattern to the cygpath arguments\n    if [ \"$GRADLE_CYGPATTERN\" != \"\" ] ; then\n        OURCYGPATTERN=\"$OURCYGPATTERN|($GRADLE_CYGPATTERN)\"\n    fi\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    i=0\n    for arg in \"$@\" ; do\n        CHECK=`echo \"$arg\"|egrep -c \"$OURCYGPATTERN\" -`\n        CHECK2=`echo \"$arg\"|egrep -c \"^-\"`                                 ### Determine if an option\n\n        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition\n            eval `echo args$i`=`cygpath --path --ignore --mixed \"$arg\"`\n        else\n            eval `echo args$i`=\"\\\"$arg\\\"\"\n        fi\n        i=$((i+1))\n    done\n    case $i in\n        (0) set -- ;;\n        (1) set -- \"$args0\" ;;\n        (2) set -- \"$args0\" \"$args1\" ;;\n        (3) set -- \"$args0\" \"$args1\" \"$args2\" ;;\n        (4) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" ;;\n        (5) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" ;;\n        (6) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" ;;\n        (7) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" ;;\n        (8) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" ;;\n        (9) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" \"$args8\" ;;\n    esac\nfi\n\n# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules\nfunction splitJvmOpts() {\n    JVM_OPTS=(\"$@\")\n}\neval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS\nJVM_OPTS[${#JVM_OPTS[*]}]=\"-Dorg.gradle.appname=$APP_BASE_NAME\"\n\nexec \"$JAVACMD\" \"${JVM_OPTS[@]}\" -classpath \"$CLASSPATH\" org.gradle.wrapper.GradleWrapperMain \"$@\"\n"
  },
  {
    "path": "gradlew.bat",
    "content": "@if \"%DEBUG%\" == \"\" @echo off\r\n@rem ##########################################################################\r\n@rem\r\n@rem  Gradle startup script for Windows\r\n@rem\r\n@rem ##########################################################################\r\n\r\n@rem Set local scope for the variables with windows NT shell\r\nif \"%OS%\"==\"Windows_NT\" setlocal\r\n\r\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\r\nset DEFAULT_JVM_OPTS=\r\n\r\nset DIRNAME=%~dp0\r\nif \"%DIRNAME%\" == \"\" set DIRNAME=.\r\nset APP_BASE_NAME=%~n0\r\nset APP_HOME=%DIRNAME%\r\n\r\n@rem Find java.exe\r\nif defined JAVA_HOME goto findJavaFromJavaHome\r\n\r\nset JAVA_EXE=java.exe\r\n%JAVA_EXE% -version >NUL 2>&1\r\nif \"%ERRORLEVEL%\" == \"0\" goto init\r\n\r\necho.\r\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\r\necho.\r\necho Please set the JAVA_HOME variable in your environment to match the\r\necho location of your Java installation.\r\n\r\ngoto fail\r\n\r\n:findJavaFromJavaHome\r\nset JAVA_HOME=%JAVA_HOME:\"=%\r\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\r\n\r\nif exist \"%JAVA_EXE%\" goto init\r\n\r\necho.\r\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\r\necho.\r\necho Please set the JAVA_HOME variable in your environment to match the\r\necho location of your Java installation.\r\n\r\ngoto fail\r\n\r\n:init\r\n@rem Get command-line arguments, handling Windowz variants\r\n\r\nif not \"%OS%\" == \"Windows_NT\" goto win9xME_args\r\nif \"%@eval[2+2]\" == \"4\" goto 4NT_args\r\n\r\n:win9xME_args\r\n@rem Slurp the command line arguments.\r\nset CMD_LINE_ARGS=\r\nset _SKIP=2\r\n\r\n:win9xME_args_slurp\r\nif \"x%~1\" == \"x\" goto execute\r\n\r\nset CMD_LINE_ARGS=%*\r\ngoto execute\r\n\r\n:4NT_args\r\n@rem Get arguments from the 4NT Shell from JP Software\r\nset CMD_LINE_ARGS=%$\r\n\r\n:execute\r\n@rem Setup the command line\r\n\r\nset CLASSPATH=%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\r\n\r\n@rem Execute Gradle\r\n\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\r\n\r\n:end\r\n@rem End local scope for the variables with windows NT shell\r\nif \"%ERRORLEVEL%\"==\"0\" goto mainEnd\r\n\r\n:fail\r\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\r\nrem the _cmd.exe /c_ return code!\r\nif  not \"\" == \"%GRADLE_EXIT_CONSOLE%\" exit 1\r\nexit /b 1\r\n\r\n:mainEnd\r\nif \"%OS%\"==\"Windows_NT\" endlocal\r\n\r\n:omega\r\n"
  },
  {
    "path": "settings.gradle",
    "content": "include ':app'\n"
  }
]