refactor(fmod): move all original files into fmod directory

This commit is contained in:
phaneron 2025-08-20 04:38:38 -04:00
parent 50fb3c6b1c
commit 35569faecc
544 changed files with 0 additions and 0 deletions

245
fmod/lib/libcelt/_kiss_fft_guts.h Executable file
View file

@ -0,0 +1,245 @@
/*
Copyright (c) 2003-2004, Mark Borgerding
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef KISS_FFT_GUTS_H
#define KISS_FFT_GUTS_H
#define MIN(a,b) ((a)<(b) ? (a):(b))
#define MAX(a,b) ((a)>(b) ? (a):(b))
/* kiss_fft.h
defines kiss_fft_scalar as either short or a float type
and defines
typedef struct { kiss_fft_scalar r; kiss_fft_scalar i; }kiss_fft_cpx; */
#include "kiss_fft.h"
#define MAXFACTORS 32
/* e.g. an fft of length 128 has 4 factors
as far as kissfft is concerned
4*4*4*2
*/
struct kiss_fft_state{
int nfft;
#ifndef FIXED_POINT
kiss_fft_scalar scale;
#endif
int factors[2*MAXFACTORS];
int *bitrev;
kiss_twiddle_cpx twiddles[1];
};
/*
Explanation of macros dealing with complex math:
C_MUL(m,a,b) : m = a*b
C_FIXDIV( c , div ) : if a fixed point impl., c /= div. noop otherwise
C_SUB( res, a,b) : res = a - b
C_SUBFROM( res , a) : res -= a
C_ADDTO( res , a) : res += a
* */
#ifdef FIXED_POINT
#include "arch.h"
#ifdef DOUBLE_PRECISION
# define FRACBITS 31
# define SAMPPROD celt_int64_t
#define SAMP_MAX 2147483647
#ifdef MIXED_PRECISION
#define TWID_MAX 32767
#define TRIG_UPSCALE 1
#else
#define TRIG_UPSCALE 65536
#define TWID_MAX 2147483647
#endif
#define EXT32(a) (a)
#else /* DOUBLE_PRECISION */
# define FRACBITS 15
# define SAMPPROD celt_int32_t
#define SAMP_MAX 32767
#define TRIG_UPSCALE 1
#define EXT32(a) EXTEND32(a)
#endif /* !DOUBLE_PRECISION */
#define SAMP_MIN -SAMP_MAX
#if defined(CHECK_OVERFLOW)
# define CHECK_OVERFLOW_OP(a,op,b) \
if ( (SAMPPROD)(a) op (SAMPPROD)(b) > SAMP_MAX || (SAMPPROD)(a) op (SAMPPROD)(b) < SAMP_MIN ) { \
fprintf(stderr,"WARNING:overflow @ " __FILE__ "(%d): (%d " #op" %d) = %ld\n",__LINE__,(a),(b),(SAMPPROD)(a) op (SAMPPROD)(b) ); }
#endif
# define smul(a,b) ( (SAMPPROD)(a)*(b) )
# define sround( x ) (kiss_fft_scalar)( ( (x) + ((SAMPPROD)1<<(FRACBITS-1)) ) >> FRACBITS )
#ifdef MIXED_PRECISION
# define S_MUL(a,b) MULT16_32_Q15(b, a)
# define C_MUL(m,a,b) \
do{ (m).r = SUB32(S_MUL((a).r,(b).r) , S_MUL((a).i,(b).i)); \
(m).i = ADD32(S_MUL((a).r,(b).i) , S_MUL((a).i,(b).r)); }while(0)
# define C_MULC(m,a,b) \
do{ (m).r = ADD32(S_MUL((a).r,(b).r) , S_MUL((a).i,(b).i)); \
(m).i = SUB32(S_MUL((a).i,(b).r) , S_MUL((a).r,(b).i)); }while(0)
# define C_MUL4(m,a,b) \
do{ (m).r = SHR(SUB32(S_MUL((a).r,(b).r) , S_MUL((a).i,(b).i)),2); \
(m).i = SHR(ADD32(S_MUL((a).r,(b).i) , S_MUL((a).i,(b).r)),2); }while(0)
# define C_MULBYSCALAR( c, s ) \
do{ (c).r = S_MUL( (c).r , s ) ;\
(c).i = S_MUL( (c).i , s ) ; }while(0)
# define DIVSCALAR(x,k) \
(x) = S_MUL( x, (TWID_MAX-((k)>>1))/(k)+1 )
# define C_FIXDIV(c,div) \
do { DIVSCALAR( (c).r , div); \
DIVSCALAR( (c).i , div); }while (0)
#define C_ADD( res, a,b)\
do {(res).r=ADD32((a).r,(b).r); (res).i=ADD32((a).i,(b).i); \
}while(0)
#define C_SUB( res, a,b)\
do {(res).r=SUB32((a).r,(b).r); (res).i=SUB32((a).i,(b).i); \
}while(0)
#define C_ADDTO( res , a)\
do {(res).r = ADD32((res).r, (a).r); (res).i = ADD32((res).i,(a).i);\
}while(0)
#define C_SUBFROM( res , a)\
do {(res).r = ADD32((res).r,(a).r); (res).i = SUB32((res).i,(a).i); \
}while(0)
#else /* MIXED_PRECISION */
# define sround4( x ) (kiss_fft_scalar)( ( (x) + ((SAMPPROD)1<<(FRACBITS-1)) ) >> (FRACBITS+2) )
# define S_MUL(a,b) sround( smul(a,b) )
# define C_MUL(m,a,b) \
do{ (m).r = sround( smul((a).r,(b).r) - smul((a).i,(b).i) ); \
(m).i = sround( smul((a).r,(b).i) + smul((a).i,(b).r) ); }while(0)
# define C_MULC(m,a,b) \
do{ (m).r = sround( smul((a).r,(b).r) + smul((a).i,(b).i) ); \
(m).i = sround( smul((a).i,(b).r) - smul((a).r,(b).i) ); }while(0)
# define C_MUL4(m,a,b) \
do{ (m).r = sround4( smul((a).r,(b).r) - smul((a).i,(b).i) ); \
(m).i = sround4( smul((a).r,(b).i) + smul((a).i,(b).r) ); }while(0)
# define C_MULBYSCALAR( c, s ) \
do{ (c).r = sround( smul( (c).r , s ) ) ;\
(c).i = sround( smul( (c).i , s ) ) ; }while(0)
# define DIVSCALAR(x,k) \
(x) = sround( smul( x, SAMP_MAX/k ) )
# define C_FIXDIV(c,div) \
do { DIVSCALAR( (c).r , div); \
DIVSCALAR( (c).i , div); }while (0)
#endif /* !MIXED_PRECISION */
#else /* not FIXED_POINT*/
#define EXT32(a) (a)
# define S_MUL(a,b) ( (a)*(b) )
#define C_MUL(m,a,b) \
do{ (m).r = (a).r*(b).r - (a).i*(b).i;\
(m).i = (a).r*(b).i + (a).i*(b).r; }while(0)
#define C_MULC(m,a,b) \
do{ (m).r = (a).r*(b).r + (a).i*(b).i;\
(m).i = (a).i*(b).r - (a).r*(b).i; }while(0)
#define C_MUL4(m,a,b) C_MUL(m,a,b)
# define C_FIXDIV(c,div) /* NOOP */
# define C_MULBYSCALAR( c, s ) \
do{ (c).r *= (s);\
(c).i *= (s); }while(0)
#endif
#ifndef CHECK_OVERFLOW_OP
# define CHECK_OVERFLOW_OP(a,op,b) /* noop */
#endif
#ifndef C_ADD
#define C_ADD( res, a,b)\
do { \
CHECK_OVERFLOW_OP((a).r,+,(b).r)\
CHECK_OVERFLOW_OP((a).i,+,(b).i)\
(res).r=(a).r+(b).r; (res).i=(a).i+(b).i; \
}while(0)
#define C_SUB( res, a,b)\
do { \
CHECK_OVERFLOW_OP((a).r,-,(b).r)\
CHECK_OVERFLOW_OP((a).i,-,(b).i)\
(res).r=(a).r-(b).r; (res).i=(a).i-(b).i; \
}while(0)
#define C_ADDTO( res , a)\
do { \
CHECK_OVERFLOW_OP((res).r,+,(a).r)\
CHECK_OVERFLOW_OP((res).i,+,(a).i)\
(res).r += (a).r; (res).i += (a).i;\
}while(0)
#define C_SUBFROM( res , a)\
do {\
CHECK_OVERFLOW_OP((res).r,-,(a).r)\
CHECK_OVERFLOW_OP((res).i,-,(a).i)\
(res).r -= (a).r; (res).i -= (a).i; \
}while(0)
#endif /* C_ADD defined */
#ifdef FIXED_POINT
/*# define KISS_FFT_COS(phase) TRIG_UPSCALE*floor(MIN(32767,MAX(-32767,.5+32768 * cos (phase))))
# define KISS_FFT_SIN(phase) TRIG_UPSCALE*floor(MIN(32767,MAX(-32767,.5+32768 * sin (phase))))*/
# define KISS_FFT_COS(phase) floor(.5+TWID_MAX*cos (phase))
# define KISS_FFT_SIN(phase) floor(.5+TWID_MAX*sin (phase))
# define HALF_OF(x) ((x)>>1)
#elif defined(USE_SIMD)
# define KISS_FFT_COS(phase) _mm_set1_ps( cos(phase) )
# define KISS_FFT_SIN(phase) _mm_set1_ps( sin(phase) )
# define HALF_OF(x) ((x)*_mm_set1_ps(.5))
#else
# define KISS_FFT_COS(phase) (kiss_fft_scalar) cos(phase)
# define KISS_FFT_SIN(phase) (kiss_fft_scalar) sin(phase)
# define HALF_OF(x) ((x)*.5)
#endif
#define kf_cexp(x,phase) \
do{ \
(x)->r = KISS_FFT_COS(phase);\
(x)->i = KISS_FFT_SIN(phase);\
}while(0)
#define kf_cexp2(x,phase) \
do{ \
(x)->r = TRIG_UPSCALE*celt_cos_norm((phase));\
(x)->i = TRIG_UPSCALE*celt_cos_norm((phase)-32768);\
}while(0)
#endif /* KISS_FFT_GUTS_H */

252
fmod/lib/libcelt/arch.h Executable file
View file

@ -0,0 +1,252 @@
/* Copyright (C) 2003-2008 Jean-Marc Valin */
/**
@file arch.h
@brief Various architecture definitions for CELT
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ARCH_H
#define ARCH_H
#include "celt_types.h"
#define CELT_SIG_SCALE 32768.
#define celt_fatal(str) _celt_fatal(str, __FILE__, __LINE__);
#ifdef ENABLE_ASSERTIONS
#define celt_assert(cond) {if (!(cond)) {celt_fatal("assertion failed: " #cond);}}
#define celt_assert2(cond, message) {if (!(cond)) {celt_fatal("assertion failed: " #cond "\n" message);}}
#else
#define celt_assert(cond)
#define celt_assert2(cond, message)
#endif
#define IMUL32(a,b) ((a)*(b))
#define UMUL32(a,b) ((celt_int32_t)(a)*(celt_int32_t)(b))
#define UMUL16_16(a,b) ((celt_int32_t)(a)*(celt_int32_t)(b))
#define ABS(x) ((x) < 0 ? (-(x)) : (x)) /**< Absolute integer value. */
#define ABS16(x) ((x) < 0 ? (-(x)) : (x)) /**< Absolute 16-bit value. */
#define MIN16(a,b) ((a) < (b) ? (a) : (b)) /**< Minimum 16-bit value. */
#define MAX16(a,b) ((a) > (b) ? (a) : (b)) /**< Maximum 16-bit value. */
#define ABS32(x) ((x) < 0 ? (-(x)) : (x)) /**< Absolute 32-bit value. */
#define MIN32(a,b) ((a) < (b) ? (a) : (b)) /**< Minimum 32-bit value. */
#define MAX32(a,b) ((a) > (b) ? (a) : (b)) /**< Maximum 32-bit value. */
#define IMIN(a,b) ((a) < (b) ? (a) : (b)) /**< Minimum int value. */
#define IMAX(a,b) ((a) > (b) ? (a) : (b)) /**< Maximum int value. */
#define UADD32(a,b) ((a)+(b))
#define USUB32(a,b) ((a)-(b))
#define PRINT_MIPS(file)
#ifdef FIXED_POINT
typedef celt_int16_t celt_word16_t;
typedef celt_int32_t celt_word32_t;
typedef celt_word32_t celt_sig_t;
typedef celt_word16_t celt_norm_t;
typedef celt_word32_t celt_ener_t;
typedef celt_word16_t celt_pgain_t;
typedef celt_word32_t celt_mask_t;
#define Q15ONE 32767
#define Q30ONE 1073741823
#define SIG_SHIFT 12
#define NORM_SCALING 16384
#define NORM_SCALING_1 (1.f/16384.f)
#define NORM_SHIFT 14
#define ENER_SCALING 16384.f
#define ENER_SCALING_1 (1.f/16384.f)
#define ENER_SHIFT 14
#define PGAIN_SCALING 32768.f
#define PGAIN_SCALING_1 (1.f/32768.f)
#define PGAIN_SHIFT 15
#define DB_SCALING 256.f
#define DB_SCALING_1 (1.f/256.f)
#define EPSILON 1
#define VERY_SMALL 0
#define VERY_LARGE32 ((celt_word32_t)2147483647)
#define VERY_LARGE16 ((celt_word16_t)32767)
#define Q15_ONE ((celt_word16_t)32767)
#define Q15_ONE_1 (1.f/32768.f)
#define SCALEIN(a) (a)
#define SCALEOUT(a) (a)
#ifdef FIXED_DEBUG
#include "fixed_debug.h"
#else
#include "fixed_generic.h"
#ifdef ARM5E_ASM
#include "fixed_arm5e.h"
#elif defined (ARM4_ASM)
#include "fixed_arm4.h"
#elif defined (BFIN_ASM)
#include "fixed_bfin.h"
#elif defined (TI_C5X_ASM)
#include "fixed_c5x.h"
#elif defined (TI_C6X_ASM)
#include "fixed_c6x.h"
#endif
#endif
#else /* FIXED_POINT */
typedef float celt_word16_t;
typedef float celt_word32_t;
typedef float celt_sig_t;
typedef float celt_norm_t;
typedef float celt_ener_t;
typedef float celt_pgain_t;
typedef float celt_mask_t;
#define Q15ONE 1.0f
#define Q30ONE 1.0f
#define NORM_SCALING 1.f
#define NORM_SCALING_1 1.f
#define ENER_SCALING 1.f
#define ENER_SCALING_1 1.f
#define PGAIN_SCALING 1.f
#define PGAIN_SCALING_1 1.f
#define DB_SCALING 1.f
#define DB_SCALING_1 1.f
#define EPSILON 1e-15f
#define VERY_SMALL 1e-15f
#define VERY_LARGE32 1e15f
#define VERY_LARGE16 1e15f
#define Q15_ONE ((celt_word16_t)1.f)
#define Q15_ONE_1 ((celt_word16_t)1.f)
#define QCONST16(x,bits) (x)
#define QCONST32(x,bits) (x)
#define NEG16(x) (-(x))
#define NEG32(x) (-(x))
#define EXTRACT16(x) (x)
#define EXTEND32(x) (x)
#define SHR16(a,shift) (a)
#define SHL16(a,shift) (a)
#define SHR32(a,shift) (a)
#define SHL32(a,shift) (a)
#define PSHR16(a,shift) (a)
#define PSHR32(a,shift) (a)
#define VSHR32(a,shift) (a)
#define SATURATE16(x,a) (x)
#define SATURATE32(x,a) (x)
#define PSHR(a,shift) (a)
#define SHR(a,shift) (a)
#define SHL(a,shift) (a)
#define SATURATE(x,a) (x)
#define ROUND16(a,shift) (a)
#define HALF32(x) (.5f*(x))
#define ADD16(a,b) ((a)+(b))
#define SUB16(a,b) ((a)-(b))
#define ADD32(a,b) ((a)+(b))
#define SUB32(a,b) ((a)-(b))
#define MULT16_16_16(a,b) ((a)*(b))
#define MULT16_16(a,b) ((celt_word32_t)(a)*(celt_word32_t)(b))
#define MAC16_16(c,a,b) ((c)+(celt_word32_t)(a)*(celt_word32_t)(b))
#define MULT16_32_Q11(a,b) ((a)*(b))
#define MULT16_32_Q13(a,b) ((a)*(b))
#define MULT16_32_Q14(a,b) ((a)*(b))
#define MULT16_32_Q15(a,b) ((a)*(b))
#define MULT16_32_Q16(a,b) ((a)*(b))
#define MULT16_32_P15(a,b) ((a)*(b))
#define MULT32_32_Q31(a,b) ((a)*(b))
#define MAC16_32_Q11(c,a,b) ((c)+(a)*(b))
#define MAC16_32_Q15(c,a,b) ((c)+(a)*(b))
#define MAC16_16_Q11(c,a,b) ((c)+(a)*(b))
#define MAC16_16_Q13(c,a,b) ((c)+(a)*(b))
#define MAC16_16_P13(c,a,b) ((c)+(a)*(b))
#define MULT16_16_Q11_32(a,b) ((a)*(b))
#define MULT16_16_Q13(a,b) ((a)*(b))
#define MULT16_16_Q14(a,b) ((a)*(b))
#define MULT16_16_Q15(a,b) ((a)*(b))
#define MULT16_16_P15(a,b) ((a)*(b))
#define MULT16_16_P13(a,b) ((a)*(b))
#define MULT16_16_P14(a,b) ((a)*(b))
#define DIV32_16(a,b) (((celt_word32_t)(a))/(celt_word16_t)(b))
#define PDIV32_16(a,b) (((celt_word32_t)(a))/(celt_word16_t)(b))
#define DIV32(a,b) (((celt_word32_t)(a))/(celt_word32_t)(b))
#define PDIV32(a,b) (((celt_word32_t)(a))/(celt_word32_t)(b))
#define SCALEIN(a) ((a)*CELT_SIG_SCALE)
#define SCALEOUT(a) ((a)*(1/CELT_SIG_SCALE))
#endif /* !FIXED_POINT */
#if defined (CONFIG_TI_C54X) || defined (CONFIG_TI_C55X)
/* 2 on TI C5x DSP */
#define BYTES_PER_CHAR 2
#define BITS_PER_CHAR 16
#define LOG2_BITS_PER_CHAR 4
#else /* CONFIG_TI_C54X */
#define BYTES_PER_CHAR 1
#define BITS_PER_CHAR 8
#define LOG2_BITS_PER_CHAR 3
#endif /* !CONFIG_TI_C54X */
#ifndef GLOBAL_STACK_SIZE
#ifdef FIXED_POINT
#define GLOBAL_STACK_SIZE 100000
#else
#define GLOBAL_STACK_SIZE 100000
#endif
#endif
#endif /* ARCH_H */

949
fmod/lib/libcelt/bands.c Executable file
View file

@ -0,0 +1,949 @@
/* (C) 2007-2008 Jean-Marc Valin, CSIRO
(C) 2008-2009 Gregory Maxwell */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <math.h>
#include "bands.h"
#include "modes.h"
#include "vq.h"
#include "cwrs.h"
#include "stack_alloc.h"
#include "os_support.h"
#include "mathops.h"
#include "rate.h"
const celt_word16_t sqrtC_1[2] = {QCONST16(1.f, 14), QCONST16(1.414214f, 14)};
#ifdef FIXED_POINT
/* Compute the amplitude (sqrt energy) in each of the bands */
void compute_band_energies(const CELTMode *m, const celt_sig_t *X, celt_ener_t *bank)
{
int i, c, N;
const celt_int16_t *eBands = m->eBands;
const int C = CHANNELS(m);
N = FRAMESIZE(m);
for (c=0;c<C;c++)
{
for (i=0;i<m->nbEBands;i++)
{
int j;
celt_word32_t maxval=0;
celt_word32_t sum = 0;
j=eBands[i]; do {
maxval = MAX32(maxval, X[j+c*N]);
maxval = MAX32(maxval, -X[j+c*N]);
} while (++j<eBands[i+1]);
if (maxval > 0)
{
int shift = celt_ilog2(maxval)-10;
j=eBands[i]; do {
sum = MAC16_16(sum, EXTRACT16(VSHR32(X[j+c*N],shift)),
EXTRACT16(VSHR32(X[j+c*N],shift)));
} while (++j<eBands[i+1]);
/* We're adding one here to make damn sure we never end up with a pitch vector that's
larger than unity norm */
bank[i+c*m->nbEBands] = EPSILON+VSHR32(EXTEND32(celt_sqrt(sum)),-shift);
} else {
bank[i+c*m->nbEBands] = EPSILON;
}
/*printf ("%f ", bank[i+c*m->nbEBands]);*/
}
}
/*printf ("\n");*/
}
/* Normalise each band such that the energy is one. */
void normalise_bands(const CELTMode *m, const celt_sig_t * celt_restrict freq, celt_norm_t * celt_restrict X, const celt_ener_t *bank)
{
int i, c, N;
const celt_int16_t *eBands = m->eBands;
const int C = CHANNELS(m);
N = FRAMESIZE(m);
for (c=0;c<C;c++)
{
i=0; do {
celt_word16_t g;
int j,shift;
celt_word16_t E;
shift = celt_zlog2(bank[i+c*m->nbEBands])-13;
E = VSHR32(bank[i+c*m->nbEBands], shift);
g = EXTRACT16(celt_rcp(SHL32(E,3)));
j=eBands[i]; do {
X[j*C+c] = MULT16_16_Q15(VSHR32(freq[j+c*N],shift-1),g);
} while (++j<eBands[i+1]);
} while (++i<m->nbEBands);
}
}
#else /* FIXED_POINT */
/* Compute the amplitude (sqrt energy) in each of the bands */
void compute_band_energies(const CELTMode *m, const celt_sig_t *X, celt_ener_t *bank)
{
int i, c, N;
const celt_int16_t *eBands = m->eBands;
const int C = CHANNELS(m);
N = FRAMESIZE(m);
for (c=0;c<C;c++)
{
for (i=0;i<m->nbEBands;i++)
{
int j;
celt_word32_t sum = 1e-10;
for (j=eBands[i];j<eBands[i+1];j++)
sum += X[j+c*N]*X[j+c*N];
bank[i+c*m->nbEBands] = sqrt(sum);
/*printf ("%f ", bank[i+c*m->nbEBands]);*/
}
}
/*printf ("\n");*/
}
#ifdef EXP_PSY
void compute_noise_energies(const CELTMode *m, const celt_sig_t *X, const celt_word16_t *tonality, celt_ener_t *bank)
{
int i, c, N;
const celt_int16_t *eBands = m->eBands;
const int C = CHANNELS(m);
N = FRAMESIZE(m);
for (c=0;c<C;c++)
{
for (i=0;i<m->nbEBands;i++)
{
int j;
celt_word32_t sum = 1e-10;
for (j=eBands[i];j<eBands[i+1];j++)
sum += X[j*C+c]*X[j+c*N]*tonality[j];
bank[i+c*m->nbEBands] = sqrt(sum);
/*printf ("%f ", bank[i+c*m->nbEBands]);*/
}
}
/*printf ("\n");*/
}
#endif
/* Normalise each band such that the energy is one. */
void normalise_bands(const CELTMode *m, const celt_sig_t * celt_restrict freq, celt_norm_t * celt_restrict X, const celt_ener_t *bank)
{
int i, c, N;
const celt_int16_t *eBands = m->eBands;
const int C = CHANNELS(m);
N = FRAMESIZE(m);
for (c=0;c<C;c++)
{
for (i=0;i<m->nbEBands;i++)
{
int j;
celt_word16_t g = 1.f/(1e-10+bank[i+c*m->nbEBands]);
for (j=eBands[i];j<eBands[i+1];j++)
X[j*C+c] = freq[j+c*N]*g;
}
}
}
#endif /* FIXED_POINT */
#ifndef DISABLE_STEREO
void renormalise_bands(const CELTMode *m, celt_norm_t * celt_restrict X)
{
int i, c;
const celt_int16_t *eBands = m->eBands;
const int C = CHANNELS(m);
for (c=0;c<C;c++)
{
i=0; do {
renormalise_vector(X+C*eBands[i]+c, QCONST16(0.70711f, 15), eBands[i+1]-eBands[i], C);
} while (++i<m->nbEBands);
}
}
#endif /* DISABLE_STEREO */
/* De-normalise the energy to produce the synthesis from the unit-energy bands */
void denormalise_bands(const CELTMode *m, const celt_norm_t * celt_restrict X, celt_sig_t * celt_restrict freq, const celt_ener_t *bank)
{
int i, c, N;
const celt_int16_t *eBands = m->eBands;
const int C = CHANNELS(m);
N = FRAMESIZE(m);
if (C>2)
celt_fatal("denormalise_bands() not implemented for >2 channels");
for (c=0;c<C;c++)
{
for (i=0;i<m->nbEBands;i++)
{
int j;
celt_word32_t g = SHR32(bank[i+c*m->nbEBands],1);
j=eBands[i]; do {
freq[j+c*N] = SHL32(MULT16_32_Q15(X[j*C+c], g),2);
} while (++j<eBands[i+1]);
}
for (i=eBands[m->nbEBands];i<eBands[m->nbEBands+1];i++)
freq[i+c*N] = 0;
}
}
/* Compute the best gain for each "pitch band" */
int compute_pitch_gain(const CELTMode *m, const celt_norm_t *X, const celt_norm_t *P, celt_pgain_t *gains)
{
int i;
int gain_sum = 0;
const celt_int16_t *pBands = m->pBands;
const int C = CHANNELS(m);
for (i=0;i<m->nbPBands;i++)
{
celt_word32_t Sxy=0, Sxx=0;
int j;
/* We know we're not going to overflow because Sxx can't be more than 1 (Q28) */
for (j=C*pBands[i];j<C*pBands[i+1];j++)
{
Sxy = MAC16_16(Sxy, X[j], P[j]);
Sxx = MAC16_16(Sxx, X[j], X[j]);
}
Sxy = SHR32(Sxy,2);
Sxx = SHR32(Sxx,2);
/* No negative gain allowed */
if (Sxy < 0)
Sxy = 0;
/* Not sure how that would happen, just making sure */
if (Sxy > Sxx)
Sxy = Sxx;
/* We need to be a bit conservative (multiply gain by 0.9), otherwise the
residual doesn't quantise well */
Sxy = MULT16_32_Q15(QCONST16(.99f, 15), Sxy);
/* gain = Sxy/Sxx */
gains[i] = EXTRACT16(celt_div(Sxy,ADD32(SHR32(Sxx, PGAIN_SHIFT),EPSILON)));
if (gains[i]>QCONST16(.5,15))
gain_sum++;
}
return gain_sum > 5;
}
#ifndef DISABLE_STEREO
static void stereo_band_mix(const CELTMode *m, celt_norm_t *X, const celt_ener_t *bank, int stereo_mode, int bandID, int dir)
{
int i = bandID;
const celt_int16_t *eBands = m->eBands;
const int C = CHANNELS(m);
int j;
celt_word16_t a1, a2;
if (stereo_mode==0)
{
/* Do mid-side when not doing intensity stereo */
a1 = QCONST16(.70711f,14);
a2 = dir*QCONST16(.70711f,14);
} else {
celt_word16_t left, right;
celt_word16_t norm;
#ifdef FIXED_POINT
int shift = celt_zlog2(MAX32(bank[i], bank[i+m->nbEBands]))-13;
#endif
left = VSHR32(bank[i],shift);
right = VSHR32(bank[i+m->nbEBands],shift);
norm = EPSILON + celt_sqrt(EPSILON+MULT16_16(left,left)+MULT16_16(right,right));
a1 = DIV32_16(SHL32(EXTEND32(left),14),norm);
a2 = dir*DIV32_16(SHL32(EXTEND32(right),14),norm);
}
for (j=eBands[i];j<eBands[i+1];j++)
{
celt_norm_t r, l;
l = X[j*C];
r = X[j*C+1];
X[j*C] = MULT16_16_Q14(a1,l) + MULT16_16_Q14(a2,r);
X[j*C+1] = MULT16_16_Q14(a1,r) - MULT16_16_Q14(a2,l);
}
}
void interleave(celt_norm_t *x, int N)
{
int i;
VARDECL(celt_norm_t, tmp);
SAVE_STACK;
ALLOC(tmp, N, celt_norm_t);
for (i=0;i<N;i++)
tmp[i] = x[i];
for (i=0;i<N>>1;i++)
{
x[i<<1] = tmp[i];
x[(i<<1)+1] = tmp[i+(N>>1)];
}
RESTORE_STACK;
}
void deinterleave(celt_norm_t *x, int N)
{
int i;
VARDECL(celt_norm_t, tmp);
SAVE_STACK;
ALLOC(tmp, N, celt_norm_t);
for (i=0;i<N;i++)
tmp[i] = x[i];
for (i=0;i<N>>1;i++)
{
x[i] = tmp[i<<1];
x[i+(N>>1)] = tmp[(i<<1)+1];
}
RESTORE_STACK;
}
#endif /* DISABLE_STEREO */
int folding_decision(const CELTMode *m, celt_norm_t *X, celt_word16_t *average, int *last_decision)
{
int i;
int NR=0;
celt_word32_t ratio = EPSILON;
const celt_int16_t * celt_restrict eBands = m->eBands;
for (i=0;i<m->nbEBands;i++)
{
int j, N;
int max_i=0;
celt_word16_t max_val=EPSILON;
celt_word32_t floor_ener=EPSILON;
celt_norm_t * celt_restrict x = X+eBands[i];
N = eBands[i+1]-eBands[i];
for (j=0;j<N;j++)
{
if (ABS16(x[j])>max_val)
{
max_val = ABS16(x[j]);
max_i = j;
}
}
#if 0
for (j=0;j<N;j++)
{
if (abs(j-max_i)>2)
floor_ener += x[j]*x[j];
}
#else
floor_ener = QCONST32(1.,28)-MULT16_16(max_val,max_val);
if (max_i < N-1)
floor_ener -= MULT16_16(x[max_i+1], x[max_i+1]);
if (max_i < N-2)
floor_ener -= MULT16_16(x[max_i+2], x[max_i+2]);
if (max_i > 0)
floor_ener -= MULT16_16(x[max_i-1], x[max_i-1]);
if (max_i > 1)
floor_ener -= MULT16_16(x[max_i-2], x[max_i-2]);
floor_ener = MAX32(floor_ener, EPSILON);
#endif
if (N>7 && eBands[i] >= m->pitchEnd)
{
celt_word16_t r;
celt_word16_t den = celt_sqrt(floor_ener);
den = MAX32(QCONST16(.02, 15), den);
r = DIV32_16(SHL32(EXTEND32(max_val),8),den);
ratio = ADD32(ratio, EXTEND32(r));
NR++;
}
}
if (NR>0)
ratio = DIV32_16(ratio, NR);
ratio = ADD32(HALF32(ratio), HALF32(*average));
if (!*last_decision)
{
*last_decision = (ratio < QCONST16(1.8,8));
} else {
*last_decision = (ratio < QCONST16(3.,8));
}
*average = EXTRACT16(ratio);
return *last_decision;
}
#ifdef FMOD_CELT_ENCODER
/* Quantisation of the residual */
void quant_bands(const CELTMode *m, celt_norm_t * celt_restrict X, celt_norm_t *P, celt_mask_t *W, int pitch_used, celt_pgain_t *pgains, const celt_ener_t *bandE, int *pulses, int shortBlocks, int fold, int total_bits, ec_enc *enc)
{
int i, j, remaining_bits, balance;
const celt_int16_t * celt_restrict eBands = m->eBands;
celt_norm_t * celt_restrict norm;
VARDECL(celt_norm_t, _norm); const celt_int16_t *pBands = m->pBands;
int pband=-1;
int B;
SAVE_STACK;
B = shortBlocks ? m->nbShortMdcts : 1;
ALLOC(_norm, eBands[m->nbEBands+1], celt_norm_t);
norm = _norm;
balance = 0;
for (i=0;i<m->nbEBands;i++)
{
int tell;
int N;
int q;
celt_word16_t n;
const celt_int16_t * const *BPbits;
int curr_balance, curr_bits;
N = eBands[i+1]-eBands[i];
BPbits = m->bits;
tell = ec_enc_tell(enc, 4);
if (i != 0)
balance -= tell;
remaining_bits = (total_bits<<BITRES)-tell-1;
curr_balance = (m->nbEBands-i);
if (curr_balance > 3)
curr_balance = 3;
curr_balance = balance / curr_balance;
q = bits2pulses(m, BPbits[i], N, pulses[i]+curr_balance);
curr_bits = pulses2bits(BPbits[i], N, q);
remaining_bits -= curr_bits;
while (remaining_bits < 0 && q > 0)
{
remaining_bits += curr_bits;
q--;
curr_bits = pulses2bits(BPbits[i], N, q);
remaining_bits -= curr_bits;
}
balance += pulses[i] + tell;
n = SHL16(celt_sqrt(eBands[i+1]-eBands[i]),11);
/* If pitch is in use and this eBand begins a pitch band, encode the pitch gain flag */
if (pitch_used && eBands[i]< m->pitchEnd && eBands[i] == pBands[pband+1])
{
int enabled = 1;
pband++;
if (remaining_bits >= 1<<BITRES) {
enabled = pgains[pband] > QCONST16(.5,15);
ec_enc_bits(enc, enabled, 1);
balance += 1<<BITRES;
}
if (enabled)
pgains[pband] = QCONST16(.9,15);
else
pgains[pband] = 0;
}
/* If pitch isn't available, use intra-frame prediction */
if ((eBands[i] >= m->pitchEnd && fold) || q<=0)
{
intra_fold(m, X+eBands[i], eBands[i+1]-eBands[i], &q, norm, P+eBands[i], eBands[i], B);
} else if (pitch_used && eBands[i] < m->pitchEnd) {
for (j=eBands[i];j<eBands[i+1];j++)
P[j] = MULT16_16_Q15(pgains[pband], P[j]);
} else {
for (j=eBands[i];j<eBands[i+1];j++)
P[j] = 0;
}
if (q > 0)
{
alg_quant(X+eBands[i], W+eBands[i], eBands[i+1]-eBands[i], q, P+eBands[i], enc);
} else {
for (j=eBands[i];j<eBands[i+1];j++)
X[j] = P[j];
}
for (j=eBands[i];j<eBands[i+1];j++)
norm[j] = MULT16_16_Q15(n,X[j]);
}
RESTORE_STACK;
}
#ifndef DISABLE_STEREO
void quant_bands_stereo(const CELTMode *m, celt_norm_t * celt_restrict X, celt_norm_t *P, celt_mask_t *W, int pitch_used, celt_pgain_t *pgains, const celt_ener_t *bandE, int *pulses, int shortBlocks, int fold, int total_bits, ec_enc *enc)
{
int i, j, remaining_bits, balance;
const celt_int16_t * celt_restrict eBands = m->eBands;
celt_norm_t * celt_restrict norm;
VARDECL(celt_norm_t, _norm);
const int C = CHANNELS(m);
const celt_int16_t *pBands = m->pBands;
int pband=-1;
int B;
celt_word16_t mid, side;
SAVE_STACK;
B = shortBlocks ? m->nbShortMdcts : 1;
ALLOC(_norm, C*eBands[m->nbEBands+1], celt_norm_t);
norm = _norm;
balance = 0;
for (i=0;i<m->nbEBands;i++)
{
int c;
int tell;
int q1, q2;
celt_word16_t n;
const celt_int16_t * const *BPbits;
int b, qb;
int N;
int curr_balance, curr_bits;
int imid, iside, itheta;
int mbits, sbits, delta;
int qalloc;
BPbits = m->bits;
N = eBands[i+1]-eBands[i];
tell = ec_enc_tell(enc, 4);
if (i != 0)
balance -= tell;
remaining_bits = (total_bits<<BITRES)-tell-1;
curr_balance = (m->nbEBands-i);
if (curr_balance > 3)
curr_balance = 3;
curr_balance = balance / curr_balance;
b = IMIN(remaining_bits+1,pulses[i]+curr_balance);
if (b<0)
b = 0;
qb = (b-2*(N-1)*(40-log2_frac(N,4)))/(32*(N-1));
if (qb > (b>>BITRES)-1)
qb = (b>>BITRES)-1;
if (qb<0)
qb = 0;
if (qb>14)
qb = 14;
stereo_band_mix(m, X, bandE, qb==0, i, 1);
mid = renormalise_vector(X+C*eBands[i], Q15ONE, N, C);
side = renormalise_vector(X+C*eBands[i]+1, Q15ONE, N, C);
#ifdef FIXED_POINT
itheta = MULT16_16_Q15(QCONST16(0.63662,15),celt_atan2p(side, mid));
#else
itheta = floor(.5+16384*0.63662*atan2(side,mid));
#endif
qalloc = log2_frac((1<<qb)+1,4);
if (qb==0)
{
itheta=0;
} else {
int shift;
shift = 14-qb;
itheta = (itheta+(1<<shift>>1))>>shift;
ec_enc_uint(enc, itheta, (1<<qb)+1);
itheta <<= shift;
}
if (itheta == 0)
{
imid = 32767;
iside = 0;
delta = -10000;
} else if (itheta == 16384)
{
imid = 0;
iside = 32767;
delta = 10000;
} else {
imid = bitexact_cos(itheta);
iside = bitexact_cos(16384-itheta);
delta = (N-1)*(log2_frac(iside,6)-log2_frac(imid,6))>>2;
}
mbits = (b-qalloc/2-delta)/2;
if (mbits > b-qalloc)
mbits = b-qalloc;
if (mbits<0)
mbits=0;
sbits = b-qalloc-mbits;
q1 = bits2pulses(m, BPbits[i], N, mbits);
q2 = bits2pulses(m, BPbits[i], N, sbits);
curr_bits = pulses2bits(BPbits[i], N, q1)+pulses2bits(BPbits[i], N, q2)+qalloc;
remaining_bits -= curr_bits;
while (remaining_bits < 0 && (q1 > 0 || q2 > 0))
{
remaining_bits += curr_bits;
if (q1>q2)
{
q1--;
curr_bits = pulses2bits(BPbits[i], N, q1)+pulses2bits(BPbits[i], N, q2)+qalloc;
} else {
q2--;
curr_bits = pulses2bits(BPbits[i], N, q1)+pulses2bits(BPbits[i], N, q2)+qalloc;
}
remaining_bits -= curr_bits;
}
balance += pulses[i] + tell;
n = SHL16(celt_sqrt((eBands[i+1]-eBands[i])),11);
/* If pitch is in use and this eBand begins a pitch band, encode the pitch gain flag */
if (pitch_used && eBands[i]< m->pitchEnd && eBands[i] == pBands[pband+1])
{
int enabled = 1;
pband++;
if (remaining_bits >= 1<<BITRES) {
enabled = pgains[pband] > QCONST16(.5,15);
ec_enc_bits(enc, enabled, 1);
balance += 1<<BITRES;
}
if (enabled)
pgains[pband] = QCONST16(.9,15);
else
pgains[pband] = 0;
}
/* If pitch isn't available, use intra-frame prediction */
if ((eBands[i] >= m->pitchEnd && fold) || (q1+q2)<=0)
{
int K[2] = {q1, q2};
intra_fold(m, X+C*eBands[i], eBands[i+1]-eBands[i], K, norm, P+C*eBands[i], eBands[i], B);
deinterleave(P+C*eBands[i], C*N);
} else if (pitch_used && eBands[i] < m->pitchEnd) {
stereo_band_mix(m, P, bandE, qb==0, i, 1);
renormalise_vector(P+C*eBands[i], Q15ONE, N, C);
renormalise_vector(P+C*eBands[i]+1, Q15ONE, N, C);
deinterleave(P+C*eBands[i], C*N);
for (j=C*eBands[i];j<C*eBands[i+1];j++)
P[j] = MULT16_16_Q15(pgains[pband], P[j]);
} else {
for (j=C*eBands[i];j<C*eBands[i+1];j++)
P[j] = 0;
}
deinterleave(X+C*eBands[i], C*N);
if (q1 > 0)
alg_quant(X+C*eBands[i], W+C*eBands[i], N, q1, P+C*eBands[i], enc);
else
for (j=C*eBands[i];j<C*eBands[i]+N;j++)
X[j] = P[j];
if (q2 > 0)
alg_quant(X+C*eBands[i]+N, W+C*eBands[i], N, q2, P+C*eBands[i]+N, enc);
else
for (j=C*eBands[i]+N;j<C*eBands[i+1];j++)
X[j] = 0;
#ifdef FIXED_POINT
mid = imid;
side = iside;
#else
mid = (1./32768)*imid;
side = (1./32768)*iside;
#endif
for (c=0;c<C;c++)
for (j=0;j<N;j++)
norm[C*(eBands[i]+j)+c] = MULT16_16_Q15(n,X[C*eBands[i]+c*N+j]);
for (j=0;j<N;j++)
X[C*eBands[i]+j] = MULT16_16_Q15(X[C*eBands[i]+j], mid);
for (j=0;j<N;j++)
X[C*eBands[i]+N+j] = MULT16_16_Q15(X[C*eBands[i]+N+j], side);
interleave(X+C*eBands[i], C*N);
stereo_band_mix(m, X, bandE, 0, i, -1);
renormalise_vector(X+C*eBands[i], Q15ONE, N, C);
renormalise_vector(X+C*eBands[i]+1, Q15ONE, N, C);
}
RESTORE_STACK;
}
#endif /* DISABLE_STEREO */
#endif /* FMOD_CELT_ENCODER */
/* Decoding of the residual */
void unquant_bands(const CELTMode *m, celt_norm_t * celt_restrict X, celt_norm_t *P, int pitch_used, celt_pgain_t *pgains, const celt_ener_t *bandE, int *pulses, int shortBlocks, int fold, int total_bits, ec_dec *dec)
{
int i, j, remaining_bits, balance;
const celt_int16_t * celt_restrict eBands = m->eBands;
celt_norm_t * celt_restrict norm;
VARDECL(celt_norm_t, _norm);
const celt_int16_t *pBands = m->pBands;
int pband=-1;
int B;
SAVE_STACK;
B = shortBlocks ? m->nbShortMdcts : 1;
ALLOC(_norm, eBands[m->nbEBands+1], celt_norm_t);
norm = _norm;
balance = 0;
for (i=0;i<m->nbEBands;i++)
{
int tell;
int N;
int q;
celt_word16_t n;
const celt_int16_t * const *BPbits;
int curr_balance, curr_bits;
N = eBands[i+1]-eBands[i];
BPbits = m->bits;
tell = ec_dec_tell(dec, 4);
if (i != 0)
balance -= tell;
remaining_bits = (total_bits<<BITRES)-tell-1;
curr_balance = (m->nbEBands-i);
if (curr_balance > 3)
curr_balance = 3;
curr_balance = balance / curr_balance;
q = bits2pulses(m, BPbits[i], N, pulses[i]+curr_balance);
curr_bits = pulses2bits(BPbits[i], N, q);
remaining_bits -= curr_bits;
while (remaining_bits < 0 && q > 0)
{
remaining_bits += curr_bits;
q--;
curr_bits = pulses2bits(BPbits[i], N, q);
remaining_bits -= curr_bits;
}
balance += pulses[i] + tell;
n = SHL16(celt_sqrt(eBands[i+1]-eBands[i]),11);
/* If pitch is in use and this eBand begins a pitch band, encode the pitch gain flag */
if (pitch_used && eBands[i] < m->pitchEnd && eBands[i] == pBands[pband+1])
{
int enabled = 1;
pband++;
if (remaining_bits >= 1<<BITRES) {
enabled = ec_dec_bits(dec, 1);
balance += 1<<BITRES;
}
if (enabled)
pgains[pband] = QCONST16(.9,15);
else
pgains[pband] = 0;
}
/* If pitch isn't available, use intra-frame prediction */
if ((eBands[i] >= m->pitchEnd && fold) || q<=0)
{
intra_fold(m, X+eBands[i], eBands[i+1]-eBands[i], &q, norm, P+eBands[i], eBands[i], B);
} else if (pitch_used && eBands[i] < m->pitchEnd) {
for (j=eBands[i];j<eBands[i+1];j++)
P[j] = MULT16_16_Q15(pgains[pband], P[j]);
} else {
for (j=eBands[i];j<eBands[i+1];j++)
P[j] = 0;
}
if (q > 0)
{
alg_unquant(X+eBands[i], eBands[i+1]-eBands[i], q, P+eBands[i], dec);
} else {
for (j=eBands[i];j<eBands[i+1];j++)
X[j] = P[j];
}
for (j=eBands[i];j<eBands[i+1];j++)
norm[j] = MULT16_16_Q15(n,X[j]);
}
RESTORE_STACK;
}
#ifndef DISABLE_STEREO
void unquant_bands_stereo(const CELTMode *m, celt_norm_t * celt_restrict X, celt_norm_t *P, int pitch_used, celt_pgain_t *pgains, const celt_ener_t *bandE, int *pulses, int shortBlocks, int fold, int total_bits, ec_dec *dec)
{
int i, j, remaining_bits, balance;
const celt_int16_t * celt_restrict eBands = m->eBands;
celt_norm_t * celt_restrict norm;
VARDECL(celt_norm_t, _norm);
const int C = CHANNELS(m);
const celt_int16_t *pBands = m->pBands;
int pband=-1;
int B;
celt_word16_t mid, side;
SAVE_STACK;
B = shortBlocks ? m->nbShortMdcts : 1;
ALLOC(_norm, C*eBands[m->nbEBands+1], celt_norm_t);
norm = _norm;
balance = 0;
for (i=0;i<m->nbEBands;i++)
{
int c;
int tell;
int q1, q2;
celt_word16_t n;
const celt_int16_t * const *BPbits;
int b, qb;
int N;
int curr_balance, curr_bits;
int imid, iside, itheta;
int mbits, sbits, delta;
int qalloc;
BPbits = m->bits;
N = eBands[i+1]-eBands[i];
tell = ec_dec_tell(dec, 4);
if (i != 0)
balance -= tell;
remaining_bits = (total_bits<<BITRES)-tell-1;
curr_balance = (m->nbEBands-i);
if (curr_balance > 3)
curr_balance = 3;
curr_balance = balance / curr_balance;
b = IMIN(remaining_bits+1,pulses[i]+curr_balance);
if (b<0)
b = 0;
qb = (b-2*(N-1)*(40-log2_frac(N,4)))/(32*(N-1));
if (qb > (b>>BITRES)-1)
qb = (b>>BITRES)-1;
if (qb>14)
qb = 14;
if (qb<0)
qb = 0;
qalloc = log2_frac((1<<qb)+1,4);
if (qb==0)
{
itheta=0;
} else {
int shift;
shift = 14-qb;
itheta = ec_dec_uint(dec, (1<<qb)+1);
itheta <<= shift;
}
if (itheta == 0)
{
imid = 32767;
iside = 0;
delta = -10000;
} else if (itheta == 16384)
{
imid = 0;
iside = 32767;
delta = 10000;
} else {
imid = bitexact_cos(itheta);
iside = bitexact_cos(16384-itheta);
delta = (N-1)*(log2_frac(iside,6)-log2_frac(imid,6))>>2;
}
mbits = (b-qalloc/2-delta)/2;
if (mbits > b-qalloc)
mbits = b-qalloc;
if (mbits<0)
mbits=0;
sbits = b-qalloc-mbits;
q1 = bits2pulses(m, BPbits[i], N, mbits);
q2 = bits2pulses(m, BPbits[i], N, sbits);
curr_bits = pulses2bits(BPbits[i], N, q1)+pulses2bits(BPbits[i], N, q2)+qalloc;
remaining_bits -= curr_bits;
while (remaining_bits < 0 && (q1 > 0 || q2 > 0))
{
remaining_bits += curr_bits;
if (q1>q2)
{
q1--;
curr_bits = pulses2bits(BPbits[i], N, q1)+pulses2bits(BPbits[i], N, q2)+qalloc;
} else {
q2--;
curr_bits = pulses2bits(BPbits[i], N, q1)+pulses2bits(BPbits[i], N, q2)+qalloc;
}
remaining_bits -= curr_bits;
}
balance += pulses[i] + tell;
n = SHL16(celt_sqrt((eBands[i+1]-eBands[i])),11);
/* If pitch is in use and this eBand begins a pitch band, encode the pitch gain flag */
if (pitch_used && eBands[i]< m->pitchEnd && eBands[i] == pBands[pband+1])
{
int enabled = 1;
pband++;
if (remaining_bits >= 1<<BITRES) {
enabled = ec_dec_bits(dec, 1);
balance += 1<<BITRES;
}
if (enabled)
pgains[pband] = QCONST16(.9,15);
else
pgains[pband] = 0;
}
/* If pitch isn't available, use intra-frame prediction */
if ((eBands[i] >= m->pitchEnd && fold) || (q1+q2)<=0)
{
int K[2] = {q1, q2};
intra_fold(m, X+C*eBands[i], eBands[i+1]-eBands[i], K, norm, P+C*eBands[i], eBands[i], B);
deinterleave(P+C*eBands[i], C*N);
} else if (pitch_used && eBands[i] < m->pitchEnd) {
stereo_band_mix(m, P, bandE, qb==0, i, 1);
renormalise_vector(P+C*eBands[i], Q15ONE, N, C);
renormalise_vector(P+C*eBands[i]+1, Q15ONE, N, C);
deinterleave(P+C*eBands[i], C*N);
for (j=C*eBands[i];j<C*eBands[i+1];j++)
P[j] = MULT16_16_Q15(pgains[pband], P[j]);
} else {
for (j=C*eBands[i];j<C*eBands[i+1];j++)
P[j] = 0;
}
deinterleave(X+C*eBands[i], C*N);
if (q1 > 0)
alg_unquant(X+C*eBands[i], N, q1, P+C*eBands[i], dec);
else
for (j=C*eBands[i];j<C*eBands[i]+N;j++)
X[j] = P[j];
if (q2 > 0)
alg_unquant(X+C*eBands[i]+N, N, q2, P+C*eBands[i]+N, dec);
else
for (j=C*eBands[i]+N;j<C*eBands[i+1];j++)
X[j] = 0;
/*orthogonalize(X+C*eBands[i], X+C*eBands[i]+N, N);*/
#ifdef FIXED_POINT
mid = imid;
side = iside;
#else
mid = (1./32768)*imid;
side = (1./32768)*iside;
#endif
for (c=0;c<C;c++)
for (j=0;j<N;j++)
norm[C*(eBands[i]+j)+c] = MULT16_16_Q15(n,X[C*eBands[i]+c*N+j]);
for (j=0;j<N;j++)
X[C*eBands[i]+j] = MULT16_16_Q15(X[C*eBands[i]+j], mid);
for (j=0;j<N;j++)
X[C*eBands[i]+N+j] = MULT16_16_Q15(X[C*eBands[i]+N+j], side);
interleave(X+C*eBands[i], C*N);
stereo_band_mix(m, X, bandE, 0, i, -1);
renormalise_vector(X+C*eBands[i], Q15ONE, N, C);
renormalise_vector(X+C*eBands[i]+1, Q15ONE, N, C);
}
RESTORE_STACK;
}
#endif /* DISABLE_STEREO */

103
fmod/lib/libcelt/bands.h Executable file
View file

@ -0,0 +1,103 @@
/* (C) 2007 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef BANDS_H
#define BANDS_H
#include "arch.h"
#include "modes.h"
#include "entenc.h"
#include "entdec.h"
#include "rate.h"
/** Compute the amplitude (sqrt energy) in each of the bands
* @param m Mode data
* @param X Spectrum
* @param bands Square root of the energy for each band (returned)
*/
void compute_band_energies(const CELTMode *m, const celt_sig_t *X, celt_ener_t *bands);
void compute_noise_energies(const CELTMode *m, const celt_sig_t *X, const celt_word16_t *tonality, celt_ener_t *bank);
/** Normalise each band of X such that the energy in each band is
equal to 1
* @param m Mode data
* @param X Spectrum (returned normalised)
* @param bands Square root of the energy for each band
*/
void normalise_bands(const CELTMode *m, const celt_sig_t * celt_restrict freq, celt_norm_t * celt_restrict X, const celt_ener_t *bands);
void renormalise_bands(const CELTMode *m, celt_norm_t * celt_restrict X);
/** Denormalise each band of X to restore full amplitude
* @param m Mode data
* @param X Spectrum (returned de-normalised)
* @param bands Square root of the energy for each band
*/
void denormalise_bands(const CELTMode *m, const celt_norm_t * celt_restrict X, celt_sig_t * celt_restrict freq, const celt_ener_t *bands);
/** Compute the pitch predictor gain for each pitch band
* @param m Mode data
* @param X Spectrum to predict
* @param P Pitch vector (normalised)
* @param gains Gain computed for each pitch band (returned)
* @param bank Square root of the energy for each band
*/
int compute_pitch_gain(const CELTMode *m, const celt_norm_t *X, const celt_norm_t *P, celt_pgain_t *gains);
int folding_decision(const CELTMode *m, celt_norm_t *X, celt_word16_t *average, int *last_decision);
/** Quantisation/encoding of the residual spectrum
* @param m Mode data
* @param X Residual (normalised)
* @param P Pitch vector (normalised)
* @param W Perceptual weighting
* @param total_bits Total number of bits that can be used for the frame (including the ones already spent)
* @param enc Entropy encoder
*/
void quant_bands(const CELTMode *m, celt_norm_t * celt_restrict X, celt_norm_t *P, celt_mask_t *W, int pitch_used, celt_pgain_t *pgains, const celt_ener_t *bandE, int *pulses, int time_domain, int fold, int total_bits, ec_enc *enc);
void quant_bands_stereo(const CELTMode *m, celt_norm_t * celt_restrict X, celt_norm_t *P, celt_mask_t *W, int pitch_used, celt_pgain_t *pgains, const celt_ener_t *bandE, int *pulses, int time_domain, int fold, int total_bits, ec_enc *enc);
/** Decoding of the residual spectrum
* @param m Mode data
* @param X Residual (normalised)
* @param P Pitch vector (normalised)
* @param total_bits Total number of bits that can be used for the frame (including the ones already spent)
* @param dec Entropy decoder
*/
void unquant_bands(const CELTMode *m, celt_norm_t * celt_restrict X, celt_norm_t *P, int pitch_used, celt_pgain_t *pgains, const celt_ener_t *bandE, int *pulses, int time_domain, int fold, int total_bits, ec_dec *dec);
void unquant_bands_stereo(const CELTMode *m, celt_norm_t * celt_restrict X, celt_norm_t *P, int pitch_used, celt_pgain_t *pgains, const celt_ener_t *bandE, int *pulses, int time_domain, int fold, int total_bits, ec_dec *dec);
void stereo_decision(const CELTMode *m, celt_norm_t * celt_restrict X, int *stereo_mode, int len);
#endif /* BANDS_H */

1635
fmod/lib/libcelt/celt.c Executable file

File diff suppressed because it is too large Load diff

284
fmod/lib/libcelt/celt.h Executable file
View file

@ -0,0 +1,284 @@
/* (C) 2007-2008 Jean-Marc Valin, CSIRO
(C) 2008 Gregory Maxwell */
/**
@file celt.h
@brief Contains all the functions for encoding and decoding audio
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CELT_H
#define CELT_H
#include "celt_types.h"
#ifdef __cplusplus
extern "C" {
#endif
#if defined(__GNUC__) && defined(CELT_BUILD)
#define EXPORT __attribute__ ((visibility ("default")))
#elif defined(WIN32)
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif
#define _celt_check_int(x) (((void)((x) == (celt_int32_t)0)), (celt_int32_t)(x))
#define _celt_check_mode_ptr_ptr(ptr) ((ptr) + ((ptr) - (CELTMode**)(ptr)))
/* Error codes */
/** No error */
#define CELT_OK 0
/** An (or more) invalid argument (e.g. out of range) */
#define CELT_BAD_ARG -1
/** The mode struct passed is invalid */
#define CELT_INVALID_MODE -2
/** An internal error was detected */
#define CELT_INTERNAL_ERROR -3
/** The data passed (e.g. compressed data to decoder) is corrupted */
#define CELT_CORRUPTED_DATA -4
/** Invalid/unsupported request number */
#define CELT_UNIMPLEMENTED -5
/** An encoder or decoder structure is invalid or already freed */
#define CELT_INVALID_STATE -6
/* Requests */
#define CELT_GET_MODE_REQUEST 1
/** Get the CELTMode used by an encoder or decoder */
#define CELT_GET_MODE(x) CELT_GET_MODE_REQUEST, _celt_check_mode_ptr_ptr(x)
#define CELT_SET_COMPLEXITY_REQUEST 2
/** Controls the complexity from 0-10 (int) */
#define CELT_SET_COMPLEXITY(x) CELT_SET_COMPLEXITY_REQUEST, _celt_check_int(x)
#define CELT_SET_PREDICTION_REQUEST 4
/** Controls the use of interframe prediction.
0=Independent frames
1=Short term interframe prediction allowed
2=Long term prediction allowed
*/
#define CELT_SET_PREDICTION(x) CELT_SET_PREDICTION_REQUEST, _celt_check_int(x)
#define CELT_SET_VBR_RATE_REQUEST 6
/** Set the target VBR rate in bits per second(int); 0=CBR (default) */
#define CELT_SET_VBR_RATE(x) CELT_SET_VBR_RATE_REQUEST, _celt_check_int(x)
/** Reset the encoder/decoder memories to zero*/
#define CELT_RESET_STATE_REQUEST 8
#define CELT_RESET_STATE CELT_RESET_STATE_REQUEST
/** GET the frame size used in the current mode */
#define CELT_GET_FRAME_SIZE 1000
/** GET the lookahead used in the current mode */
#define CELT_GET_LOOKAHEAD 1001
/** GET the number of channels used in the current mode */
#define CELT_GET_NB_CHANNELS 1002
/** GET the sample rate used in the current mode */
#define CELT_GET_SAMPLE_RATE 1003
/** GET the bit-stream version for compatibility check */
#define CELT_GET_BITSTREAM_VERSION 2000
/** Contains the state of an encoder. One encoder state is needed
for each stream. It is initialised once at the beginning of the
stream. Do *not* re-initialise the state for every frame.
@brief Encoder state
*/
typedef struct CELTEncoder CELTEncoder;
/** State of the decoder. One decoder state is needed for each stream.
It is initialised once at the beginning of the stream. Do *not*
re-initialise the state for every frame */
typedef struct CELTDecoder CELTDecoder;
/** The mode contains all the information necessary to create an
encoder. Both the encoder and decoder need to be initialised
with exactly the same mode, otherwise the quality will be very
bad */
typedef struct CELTMode CELTMode;
/** \defgroup codec Encoding and decoding */
/* @{ */
/* Mode calls */
/** Creates a new mode struct. This will be passed to an encoder or
decoder. The mode MUST NOT BE DESTROYED until the encoders and
decoders that use it are destroyed as well.
@param Fs Sampling rate (32000 to 96000 Hz)
@param channels Number of channels
@param frame_size Number of samples (per channel) to encode in each
packet (even values; 64 - 512)
@param error Returned error code (if NULL, no error will be returned)
@return A newly created mode
*/
EXPORT CELTMode *celt_mode_create(celt_int32_t Fs, int channels, int frame_size, int *error);
/** Destroys a mode struct. Only call this after all encoders and
decoders using this mode are destroyed as well.
@param mode Mode to be destroyed
*/
EXPORT void celt_mode_destroy(CELTMode *mode);
/** Query information from a mode */
EXPORT int celt_mode_info(const CELTMode *mode, int request, celt_int32_t *value);
/* Encoder stuff */
/** Creates a new encoder state. Each stream needs its own encoder
state (can't be shared across simultaneous streams).
@param mode Contains all the information about the characteristics of
* the stream (must be the same characteristics as used for the
* decoder)
@return Newly created encoder state.
*/
EXPORT CELTEncoder *celt_encoder_create(const CELTMode *mode);
/** Destroys a an encoder state.
@param st Encoder state to be destroyed
*/
EXPORT void celt_encoder_destroy(CELTEncoder *st);
/** Encodes a frame of audio.
@param st Encoder state
@param pcm PCM audio in float format, with a normal range of ±1.0.
* Samples with a range beyond ±1.0 are supported but will
* be clipped by decoders using the integer API and should
* only be used if it is known that the far end supports
* extended dynmaic range. There must be exactly
* frame_size samples per channel.
@param optional_synthesis If not NULL, the encoder copies the audio signal that
* the decoder would decode. It is the same as calling the
* decoder on the compressed data, just faster.
* This may alias pcm.
@param compressed The compressed data is written here. This may not alias pcm or
* optional_synthesis.
@param nbCompressedBytes Maximum number of bytes to use for compressing the frame
* (can change from one frame to another)
@return Number of bytes written to "compressed". Will be the same as
* "nbCompressedBytes" unless the stream is VBR and will never be larger.
* If negative, an error has occurred (see error codes). It is IMPORTANT that
* the length returned be somehow transmitted to the decoder. Otherwise, no
* decoding is possible.
*/
EXPORT int celt_encode_float(CELTEncoder *st, const float *pcm, float *optional_synthesis, unsigned char *compressed, int nbCompressedBytes);
/** Encodes a frame of audio.
@param st Encoder state
@param pcm PCM audio in signed 16-bit format (native endian). There must be
* exactly frame_size samples per channel.
@param optional_synthesis If not NULL, the encoder copies the audio signal that
* the decoder would decode. It is the same as calling the
* decoder on the compressed data, just faster.
* This may alias pcm.
@param compressed The compressed data is written here. This may not alias pcm or
* optional_synthesis.
@param nbCompressedBytes Maximum number of bytes to use for compressing the frame
* (can change from one frame to another)
@return Number of bytes written to "compressed". Will be the same as
* "nbCompressedBytes" unless the stream is VBR and will never be larger.
* If negative, an error has occurred (see error codes). It is IMPORTANT that
* the length returned be somehow transmitted to the decoder. Otherwise, no
* decoding is possible.
*/
EXPORT int celt_encode(CELTEncoder *st, const celt_int16_t *pcm, celt_int16_t *optional_synthesis, unsigned char *compressed, int nbCompressedBytes);
/** Query and set encoder parameters
@param st Encoder state
@param request Parameter to change or query
@param value Pointer to a 32-bit int value
@return Error code
*/
EXPORT int celt_encoder_ctl(CELTEncoder * st, int request, ...);
/* Decoder stuff */
/** Creates a new decoder state. Each stream needs its own decoder state (can't
be shared across simultaneous streams).
@param mode Contains all the information about the characteristics of the
stream (must be the same characteristics as used for the encoder)
@return Newly created decoder state.
*/
EXPORT CELTDecoder *celt_decoder_create(const CELTMode *mode);
/** CPS - Create CELTDecoder with no mode stuff set. celt_decoder_setmode
must be called before use. (FMOD)
*/
EXPORT CELTDecoder *fmod_celt_decoder_create_only(char *membuffer);
/** CPS - Set the decoder mode after it has been created.
*/
EXPORT void fmod_celt_decoder_setmode(CELTDecoder *st, CELTMode *mode);
/** Destroys a a decoder state.
@param st Decoder state to be destroyed
*/
EXPORT void celt_decoder_destroy(CELTDecoder *st);
/** Decodes a frame of audio.
@param st Decoder state
@param data Compressed data produced by an encoder
@param len Number of bytes to read from "data". This MUST be exactly the number
of bytes returned by the encoder. Using a larger value WILL NOT WORK.
@param pcm One frame (frame_size samples per channel) of decoded PCM will be
returned here in float format.
@return Error code.
*/
EXPORT int celt_decode_float(CELTDecoder * celt_restrict st, const unsigned char *data, int len, float * celt_restrict pcm);
/** Decodes a frame of audio.
@param st Decoder state
@param data Compressed data produced by an encoder
@param len Number of bytes to read from "data". This MUST be exactly the number
of bytes returned by the encoder. Using a larger value WILL NOT WORK.
@param pcm One frame (frame_size samples per channel) of decoded PCM will be
returned here in 16-bit PCM format (native endian).
@return Error code.
*/
EXPORT int celt_decode(CELTDecoder * celt_restrict st, const unsigned char *data, int len, celt_int16_t * celt_restrict pcm);
/** Query and set decoder parameters
@param st Decoder state
@param request Parameter to change or query
@param value Pointer to a 32-bit int value
@return Error code
*/
EXPORT int celt_decoder_ctl(CELTDecoder * celt_restrict st, int request, ...);
/* @} */
#ifdef __cplusplus
}
#endif
#endif /*CELT_H */

69
fmod/lib/libcelt/celt_header.h Executable file
View file

@ -0,0 +1,69 @@
/* (C) 2008 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CELT_HEADER_H
#define CELT_HEADER_H
#ifdef __cplusplus
extern "C" {
#endif
#include "celt.h"
#include "celt_types.h"
/** Header data to be used for Ogg files (or possibly other encapsulation)
@brief Header data
*/
typedef struct {
char codec_id[8]; /**< MUST be "CELT " (four spaces) */
char codec_version[20]; /**< Version used (as string) */
celt_int32_t version_id; /**< Version id (negative for until stream is frozen) */
celt_int32_t header_size; /**< Size of this header */
celt_int32_t sample_rate; /**< Sampling rate of the original audio */
celt_int32_t nb_channels; /**< Number of channels */
celt_int32_t frame_size; /**< Samples per frame (per channel) */
celt_int32_t overlap; /**< Overlapping samples (per channel) */
celt_int32_t bytes_per_packet; /**< Number of bytes per compressed packet (0 if unknown) */
celt_int32_t extra_headers; /**< Number of additional headers that follow this header */
} CELTHeader;
/** Creates a basic header struct */
EXPORT int celt_header_init(CELTHeader *header, const CELTMode *m);
EXPORT int celt_header_to_packet(const CELTHeader *header, unsigned char *packet, celt_uint32_t size);
EXPORT int celt_header_from_packet(const unsigned char *packet, celt_uint32_t size, CELTHeader *header);
#ifdef __cplusplus
}
#endif
#endif /* CELT_HEADER_H */

178
fmod/lib/libcelt/celt_types.h Executable file
View file

@ -0,0 +1,178 @@
/* celt_types.h taken from libogg */
/********************************************************************
* *
* THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
* by the Xiph.Org Foundation http://www.xiph.org/ *
* *
********************************************************************
function: #ifdef jail to whip a few platforms into the UNIX ideal.
last mod: $Id: os_types.h 7524 2004-08-11 04:20:36Z conrad $
********************************************************************/
/**
@file celt_types.h
@brief CELT types
*/
#ifndef _CELT_TYPES_H
#define _CELT_TYPES_H
#include "../../src/fmod_types.h"
/* Use the real stdint.h if it's there (taken from Paul Hsieh's pstdint.h) */
#if (defined(__STDC__) && __STDC__ && __STDC_VERSION__ >= 199901L) || (defined(__GNUC__) && (defined(_STDINT_H) || defined(_STDINT_H_)) || defined (HAVE_STDINT_H))
#include <stdint.h>
typedef int16_t celt_int16_t;
typedef uint16_t celt_uint16_t;
typedef int32_t celt_int32_t;
typedef uint32_t celt_uint32_t;
typedef int64_t celt_int64_t;
typedef uint64_t celt_uint64_t;
#define celt_restrict __restrict__
#elif defined(_WIN32)
# if defined(__CYGWIN__)
# include <_G_config.h>
typedef _G_int32_t celt_int32_t;
typedef _G_uint32_t celt_uint32_t;
typedef _G_int16_t celt_int16_t;
typedef _G_uint16_t celt_uint16_t;
typedef _G_int64_t celt_int64_t;
typedef _G_uint64_t celt_uint64_t;
# elif defined(__MINGW32__)
typedef short celt_int16_t;
typedef unsigned short celt_uint16_t;
typedef int celt_int32_t;
typedef unsigned int celt_uint32_t;
typedef long long celt_int64_t;
typedef unsigned long long celt_uint64_t;
# elif defined(__MWERKS__)
typedef int celt_int32_t;
typedef unsigned int celt_uint32_t;
typedef short celt_int16_t;
typedef unsigned short celt_uint16_t;
typedef long long celt_int64_t;
typedef unsigned long long celt_uint64_t;
# else
/* MSVC/Borland */
typedef __int32 celt_int32_t;
typedef unsigned __int32 celt_uint32_t;
typedef __int16 celt_int16_t;
typedef unsigned __int16 celt_uint16_t;
typedef __int64 celt_int64_t;
typedef unsigned __int64 celt_uint64_t;
#define celt_restrict __restrict
# endif
#elif defined(__MACOS__)
# include <sys/types.h>
typedef SInt16 celt_int16_t;
typedef UInt16 celt_uint16_t;
typedef SInt32 celt_int32_t;
typedef UInt32 celt_uint32_t;
typedef SInt64 celt_int64_t;
typedef UInt64 celt_uint64_t;
#elif (defined(__APPLE__) && defined(__MACH__)) /* MacOS X Framework build */
# include <sys/types.h>
typedef int16_t celt_int16_t;
typedef u_int16_t celt_uint16_t;
typedef int32_t celt_int32_t;
typedef u_int32_t celt_uint32_t;
typedef int64_t celt_int64_t;
typedef u_int64_t celt_uint64_t;
#define celt_restrict __restrict__
#elif defined(__BEOS__)
/* Be */
# include <inttypes.h>
typedef int16_t celt_int16_t;
typedef u_int16_t celt_uint16_t;
typedef int32_t celt_int32_t;
typedef u_int32_t celt_uint32_t;
typedef int64_t celt_int64_t;
typedef u_int64_t celt_uint64_t;
#elif defined (__EMX__)
/* OS/2 GCC */
typedef short celt_int16_t;
typedef unsigned short celt_uint16_t;
typedef int celt_int32_t;
typedef unsigned int celt_uint32_t;
typedef long long celt_int64_t;
typedef unsigned long long celt_uint64_t;
#elif defined (DJGPP)
/* DJGPP */
typedef short celt_int16_t;
typedef int celt_int32_t;
typedef unsigned int celt_uint32_t;
typedef long long celt_int64_t;
typedef unsigned long long celt_uint64_t;
#elif defined(R5900)
/* PS2 EE */
typedef int celt_int32_t;
typedef unsigned celt_uint32_t;
typedef short celt_int16_t;
typedef long celt_int64_t;
typedef unsigned long celt_uint64_t;
#elif defined(__SYMBIAN32__)
/* Symbian GCC */
typedef signed short celt_int16_t;
typedef unsigned short celt_uint16_t;
typedef signed int celt_int32_t;
typedef unsigned int celt_uint32_t;
typedef long long int celt_int64_t;
typedef unsigned long long int celt_uint64_t;
#elif defined(CONFIG_TI_C54X) || defined (CONFIG_TI_C55X)
typedef short celt_int16_t;
typedef unsigned short celt_uint16_t;
typedef long celt_int32_t;
typedef unsigned long celt_uint32_t;
typedef long long celt_int64_t;
typedef unsigned long long celt_uint64_t;
#elif defined(CONFIG_TI_C6X)
typedef short celt_int16_t;
typedef unsigned short celt_uint16_t;
typedef int celt_int32_t;
typedef unsigned int celt_uint32_t;
typedef long long int celt_int64_t;
typedef unsigned long long int celt_uint64_t;
#else
/* Give up, take a reasonable guess */
typedef short celt_int16_t;
typedef unsigned short celt_uint16_t;
typedef int celt_int32_t;
typedef unsigned int celt_uint32_t;
typedef long long celt_int64_t;
typedef unsigned long long celt_uint64_t;
#define celt_restrict __restrict__
#endif
#endif /* _CELT_TYPES_H */

923
fmod/lib/libcelt/cwrs.c Executable file
View file

@ -0,0 +1,923 @@
/* (C) 2007-2008 Timothy B. Terriberry
(C) 2008 Jean-Marc Valin */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "os_support.h"
#include <stdlib.h>
#include <string.h>
#include "cwrs.h"
#include "mathops.h"
#include "arch.h"
/*Guaranteed to return a conservatively large estimate of the binary logarithm
with frac bits of fractional precision.
Tested for all possible 32-bit inputs with frac=4, where the maximum
overestimation is 0.06254243 bits.*/
int log2_frac(ec_uint32 val, int frac)
{
int l;
l=EC_ILOG(val);
if(val&val-1){
/*This is (val>>l-16), but guaranteed to round up, even if adding a bias
before the shift would cause overflow (e.g., for 0xFFFFxxxx).*/
if(l>16)val=(val>>l-16)+((val&(1<<l-16)-1)+(1<<l-16)-1>>l-16);
else val<<=16-l;
l=l-1<<frac;
/*Note that we always need one iteration, since the rounding up above means
that we might need to adjust the integer part of the logarithm.*/
do{
int b;
b=(int)(val>>16);
l+=b<<frac;
val=val+b>>b;
val=val*val+0x7FFF>>15;
}
while(frac-->0);
/*If val is not exactly 0x8000, then we have to round up the remainder.*/
return l+(val>0x8000);
}
/*Exact powers of two require no rounding.*/
else return l-1<<frac;
}
#define MASK32 (0xFFFFFFFF)
/*INV_TABLE[i] holds the multiplicative inverse of (2*i+1) mod 2**32.*/
static const celt_uint32_t INV_TABLE[128]={
0x00000001,0xAAAAAAAB,0xCCCCCCCD,0xB6DB6DB7,
0x38E38E39,0xBA2E8BA3,0xC4EC4EC5,0xEEEEEEEF,
0xF0F0F0F1,0x286BCA1B,0x3CF3CF3D,0xE9BD37A7,
0xC28F5C29,0x684BDA13,0x4F72C235,0xBDEF7BDF,
0x3E0F83E1,0x8AF8AF8B,0x914C1BAD,0x96F96F97,
0xC18F9C19,0x2FA0BE83,0xA4FA4FA5,0x677D46CF,
0x1A1F58D1,0xFAFAFAFB,0x8C13521D,0x586FB587,
0xB823EE09,0xA08AD8F3,0xC10C9715,0xBEFBEFBF,
0xC0FC0FC1,0x07A44C6B,0xA33F128D,0xE327A977,
0xC7E3F1F9,0x962FC963,0x3F2B3885,0x613716AF,
0x781948B1,0x2B2E43DB,0xFCFCFCFD,0x6FD0EB67,
0xFA3F47E9,0xD2FD2FD3,0x3F4FD3F5,0xD4E25B9F,
0x5F02A3A1,0xBF5A814B,0x7C32B16D,0xD3431B57,
0xD8FD8FD9,0x8D28AC43,0xDA6C0965,0xDB195E8F,
0x0FDBC091,0x61F2A4BB,0xDCFDCFDD,0x46FDD947,
0x56BE69C9,0xEB2FDEB3,0x26E978D5,0xEFDFBF7F,
0x0FE03F81,0xC9484E2B,0xE133F84D,0xE1A8C537,
0x077975B9,0x70586723,0xCD29C245,0xFAA11E6F,
0x0FE3C071,0x08B51D9B,0x8CE2CABD,0xBF937F27,
0xA8FE53A9,0x592FE593,0x2C0685B5,0x2EB11B5F,
0xFCD1E361,0x451AB30B,0x72CFE72D,0xDB35A717,
0xFB74A399,0xE80BFA03,0x0D516325,0x1BCB564F,
0xE02E4851,0xD962AE7B,0x10F8ED9D,0x95AEDD07,
0xE9DC0589,0xA18A4473,0xEA53FA95,0xEE936F3F,
0x90948F41,0xEAFEAFEB,0x3D137E0D,0xEF46C0F7,
0x028C1979,0x791064E3,0xC04FEC05,0xE115062F,
0x32385831,0x6E68575B,0xA10D387D,0x6FECF2E7,
0x3FB47F69,0xED4BFB53,0x74FED775,0xDB43BB1F,
0x87654321,0x9BA144CB,0x478BBCED,0xBFB912D7,
0x1FDCD759,0x14B2A7C3,0xCB125CE5,0x437B2E0F,
0x10FEF011,0xD2B3183B,0x386CAB5D,0xEF6AC0C7,
0x0E64C149,0x9A020A33,0xE6B41C55,0xFEFEFEFF
};
/*Computes (_a*_b-_c)/(2*_d+1) when the quotient is known to be exact.
_a, _b, _c, and _d may be arbitrary so long as the arbitrary precision result
fits in 32 bits, but currently the table for multiplicative inverses is only
valid for _d<128.*/
static FMOD_INLINE celt_uint32_t imusdiv32odd(celt_uint32_t _a,celt_uint32_t _b,
celt_uint32_t _c,int _d){
return (_a*_b-_c)*INV_TABLE[_d]&MASK32;
}
/*Computes (_a*_b-_c)/_d when the quotient is known to be exact.
_d does not actually have to be even, but imusdiv32odd will be faster when
it's odd, so you should use that instead.
_a and _d are assumed to be small (e.g., _a*_d fits in 32 bits; currently the
table for multiplicative inverses is only valid for _d<=256).
_b and _c may be arbitrary so long as the arbitrary precision reuslt fits in
32 bits.*/
static FMOD_INLINE celt_uint32_t imusdiv32even(celt_uint32_t _a,celt_uint32_t _b,
celt_uint32_t _c,int _d){
celt_uint32_t inv;
int mask;
int shift;
int one;
celt_assert(_d>0);
shift=EC_ILOG(_d^_d-1);
celt_assert(_d<=256);
inv=INV_TABLE[_d-1>>shift];
shift--;
one=1<<shift;
mask=one-1;
return (_a*(_b>>shift)-(_c>>shift)+
(_a*(_b&mask)+one-(_c&mask)>>shift)-1)*inv&MASK32;
}
/*Compute floor(sqrt(_val)) with exact arithmetic.
This has been tested on all possible 32-bit inputs.*/
static unsigned isqrt32(celt_uint32_t _val){
unsigned b;
unsigned g;
int bshift;
/*Uses the second method from
http://www.azillionmonkeys.com/qed/sqroot.html
The main idea is to search for the largest binary digit b such that
(g+b)*(g+b) <= _val, and add it to the solution g.*/
g=0;
bshift=EC_ILOG(_val)-1>>1;
b=1U<<bshift;
do{
celt_uint32_t t;
t=((celt_uint32_t)g<<1)+b<<bshift;
if(t<=_val){
g+=b;
_val-=t;
}
b>>=1;
bshift--;
}
while(bshift>=0);
return g;
}
#if 0
/*Compute floor(sqrt(_val)) with exact arithmetic.
This has been tested on all possible 36-bit inputs.*/
static celt_uint32_t isqrt36(celt_uint64_t _val){
celt_uint32_t val32;
celt_uint32_t b;
celt_uint32_t g;
int bshift;
g=0;
b=0x20000;
for(bshift=18;bshift-->13;){
celt_uint64_t t;
t=((celt_uint64_t)g<<1)+b<<bshift;
if(t<=_val){
g+=b;
_val-=t;
}
b>>=1;
}
val32=(celt_uint32_t)_val;
for(;bshift>=0;bshift--){
celt_uint32_t t;
t=(g<<1)+b<<bshift;
if(t<=val32){
g+=b;
val32-=t;
}
b>>=1;
}
return g;
}
#endif
/*Although derived separately, the pulse vector coding scheme is equivalent to
a Pyramid Vector Quantizer \cite{Fis86}.
Some additional notes about an early version appear at
http://people.xiph.org/~tterribe/notes/cwrs.html, but the codebook ordering
and the definitions of some terms have evolved since that was written.
The conversion from a pulse vector to an integer index (encoding) and back
(decoding) is governed by two related functions, V(N,K) and U(N,K).
V(N,K) = the number of combinations, with replacement, of N items, taken K
at a time, when a sign bit is added to each item taken at least once (i.e.,
the number of N-dimensional unit pulse vectors with K pulses).
One way to compute this is via
V(N,K) = K>0 ? sum(k=1...K,2**k*choose(N,k)*choose(K-1,k-1)) : 1,
where choose() is the binomial function.
A table of values for N<10 and K<10 looks like:
V[10][10] = {
{1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 2, 2, 2, 2, 2, 2, 2, 2, 2},
{1, 4, 8, 12, 16, 20, 24, 28, 32, 36},
{1, 6, 18, 38, 66, 102, 146, 198, 258, 326},
{1, 8, 32, 88, 192, 360, 608, 952, 1408, 1992},
{1, 10, 50, 170, 450, 1002, 1970, 3530, 5890, 9290},
{1, 12, 72, 292, 912, 2364, 5336, 10836, 20256, 35436},
{1, 14, 98, 462, 1666, 4942, 12642, 28814, 59906, 115598},
{1, 16, 128, 688, 2816, 9424, 27008, 68464, 157184, 332688},
{1, 18, 162, 978, 4482, 16722, 53154, 148626, 374274, 864146}
};
U(N,K) = the number of such combinations wherein N-1 objects are taken at
most K-1 at a time.
This is given by
U(N,K) = sum(k=0...K-1,V(N-1,k))
= K>0 ? (V(N-1,K-1) + V(N,K-1))/2 : 0.
The latter expression also makes clear that U(N,K) is half the number of such
combinations wherein the first object is taken at least once.
Although it may not be clear from either of these definitions, U(N,K) is the
natural function to work with when enumerating the pulse vector codebooks,
not V(N,K).
U(N,K) is not well-defined for N=0, but with the extension
U(0,K) = K>0 ? 0 : 1,
the function becomes symmetric: U(N,K) = U(K,N), with a similar table:
U[10][10] = {
{1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{0, 1, 3, 5, 7, 9, 11, 13, 15, 17},
{0, 1, 5, 13, 25, 41, 61, 85, 113, 145},
{0, 1, 7, 25, 63, 129, 231, 377, 575, 833},
{0, 1, 9, 41, 129, 321, 681, 1289, 2241, 3649},
{0, 1, 11, 61, 231, 681, 1683, 3653, 7183, 13073},
{0, 1, 13, 85, 377, 1289, 3653, 8989, 19825, 40081},
{0, 1, 15, 113, 575, 2241, 7183, 19825, 48639, 108545},
{0, 1, 17, 145, 833, 3649, 13073, 40081, 108545, 265729}
};
With this extension, V(N,K) may be written in terms of U(N,K):
V(N,K) = U(N,K) + U(N,K+1)
for all N>=0, K>=0.
Thus U(N,K+1) represents the number of combinations where the first element
is positive or zero, and U(N,K) represents the number of combinations where
it is negative.
With a large enough table of U(N,K) values, we could write O(N) encoding
and O(min(N*log(K),N+K)) decoding routines, but such a table would be
prohibitively large for small embedded devices (K may be as large as 32767
for small N, and N may be as large as 200).
Both functions obey the same recurrence relation:
V(N,K) = V(N-1,K) + V(N,K-1) + V(N-1,K-1),
U(N,K) = U(N-1,K) + U(N,K-1) + U(N-1,K-1),
for all N>0, K>0, with different initial conditions at N=0 or K=0.
This allows us to construct a row of one of the tables above given the
previous row or the next row.
Thus we can derive O(NK) encoding and decoding routines with O(K) memory
using only addition and subtraction.
When encoding, we build up from the U(2,K) row and work our way forwards.
When decoding, we need to start at the U(N,K) row and work our way backwards,
which requires a means of computing U(N,K).
U(N,K) may be computed from two previous values with the same N:
U(N,K) = ((2*N-1)*U(N,K-1) - U(N,K-2))/(K-1) + U(N,K-2)
for all N>1, and since U(N,K) is symmetric, a similar relation holds for two
previous values with the same K:
U(N,K>1) = ((2*K-1)*U(N-1,K) - U(N-2,K))/(N-1) + U(N-2,K)
for all K>1.
This allows us to construct an arbitrary row of the U(N,K) table by starting
with the first two values, which are constants.
This saves roughly 2/3 the work in our O(NK) decoding routine, but costs O(K)
multiplications.
Similar relations can be derived for V(N,K), but are not used here.
For N>0 and K>0, U(N,K) and V(N,K) take on the form of an (N-1)-degree
polynomial for fixed N.
The first few are
U(1,K) = 1,
U(2,K) = 2*K-1,
U(3,K) = (2*K-2)*K+1,
U(4,K) = (((4*K-6)*K+8)*K-3)/3,
U(5,K) = ((((2*K-4)*K+10)*K-8)*K+3)/3,
and
V(1,K) = 2,
V(2,K) = 4*K,
V(3,K) = 4*K*K+2,
V(4,K) = 8*(K*K+2)*K/3,
V(5,K) = ((4*K*K+20)*K*K+6)/3,
for all K>0.
This allows us to derive O(N) encoding and O(N*log(K)) decoding routines for
small N (and indeed decoding is also O(N) for N<3).
@ARTICLE{Fis86,
author="Thomas R. Fischer",
title="A Pyramid Vector Quantizer",
journal="IEEE Transactions on Information Theory",
volume="IT-32",
number=4,
pages="568--583",
month=Jul,
year=1986
}*/
/*Determines if V(N,K) fits in a 32-bit unsigned integer.
N and K are themselves limited to 15 bits.*/
int fits_in32(int _n, int _k)
{
static const celt_int16_t maxN[15] = {
32767, 32767, 32767, 1476, 283, 109, 60, 40,
29, 24, 20, 18, 16, 14, 13};
static const celt_int16_t maxK[15] = {
32767, 32767, 32767, 32767, 1172, 238, 95, 53,
36, 27, 22, 18, 16, 15, 13};
if (_n>=14)
{
if (_k>=14)
return 0;
else
return _n <= maxN[_k];
} else {
return _k <= maxK[_n];
}
}
/*Compute U(1,_k).*/
static FMOD_INLINE unsigned ucwrs1(int _k){
return _k?1:0;
}
/*Compute V(1,_k).*/
static FMOD_INLINE unsigned ncwrs1(int _k){
return _k?2:1;
}
/*Compute U(2,_k).
Note that this may be called with _k=32768 (maxK[2]+1).*/
static FMOD_INLINE unsigned ucwrs2(unsigned _k){
return _k?_k+(_k-1):0;
}
/*Compute V(2,_k).*/
static FMOD_INLINE celt_uint32_t ncwrs2(int _k){
return _k?4*(celt_uint32_t)_k:1;
}
/*Compute U(3,_k).
Note that this may be called with _k=32768 (maxK[3]+1).*/
static FMOD_INLINE celt_uint32_t ucwrs3(unsigned _k){
return _k?(2*(celt_uint32_t)_k-2)*_k+1:0;
}
/*Compute V(3,_k).*/
static FMOD_INLINE celt_uint32_t ncwrs3(int _k){
return _k?2*(2*(unsigned)_k*(celt_uint32_t)_k+1):1;
}
/*Compute U(4,_k).*/
static FMOD_INLINE celt_uint32_t ucwrs4(int _k){
return _k?imusdiv32odd(2*_k,(2*_k-3)*(celt_uint32_t)_k+4,3,1):0;
}
/*Compute V(4,_k).*/
static FMOD_INLINE celt_uint32_t ncwrs4(int _k){
return _k?((_k*(celt_uint32_t)_k+2)*_k)/3<<3:1;
}
/*Compute U(5,_k).*/
static FMOD_INLINE celt_uint32_t ucwrs5(int _k){
return _k?(((((_k-2)*(unsigned)_k+5)*(celt_uint32_t)_k-4)*_k)/3<<1)+1:0;
}
/*Compute V(5,_k).*/
static FMOD_INLINE celt_uint32_t ncwrs5(int _k){
return _k?(((_k*(unsigned)_k+5)*(celt_uint32_t)_k*_k)/3<<2)+2:1;
}
/*Computes the next row/column of any recurrence that obeys the relation
u[i][j]=u[i-1][j]+u[i][j-1]+u[i-1][j-1].
_ui0 is the base case for the new row/column.*/
static FMOD_INLINE void unext(celt_uint32_t *_ui,unsigned _len,celt_uint32_t _ui0){
celt_uint32_t ui1;
unsigned j;
/*This do-while will overrun the array if we don't have storage for at least
2 values.*/
j=1; do {
ui1=UADD32(UADD32(_ui[j],_ui[j-1]),_ui0);
_ui[j-1]=_ui0;
_ui0=ui1;
} while (++j<_len);
_ui[j-1]=_ui0;
}
/*Computes the previous row/column of any recurrence that obeys the relation
u[i-1][j]=u[i][j]-u[i][j-1]-u[i-1][j-1].
_ui0 is the base case for the new row/column.*/
static FMOD_INLINE void uprev(celt_uint32_t *_ui,unsigned _n,celt_uint32_t _ui0){
celt_uint32_t ui1;
unsigned j;
/*This do-while will overrun the array if we don't have storage for at least
2 values.*/
j=1; do {
ui1=USUB32(USUB32(_ui[j],_ui[j-1]),_ui0);
_ui[j-1]=_ui0;
_ui0=ui1;
} while (++j<_n);
_ui[j-1]=_ui0;
}
/*Compute V(_n,_k), as well as U(_n,0..._k+1).
_u: On exit, _u[i] contains U(_n,i) for i in [0..._k+1].*/
static celt_uint32_t ncwrs_urow(unsigned _n,unsigned _k,celt_uint32_t *_u){
celt_uint32_t um2;
unsigned len;
unsigned k;
len=_k+2;
/*We require storage at least 3 values (e.g., _k>0).*/
celt_assert(len>=3);
_u[0]=0;
_u[1]=um2=1;
if(_n<=6 || _k>255){
/*If _n==0, _u[0] should be 1 and the rest should be 0.*/
/*If _n==1, _u[i] should be 1 for i>1.*/
celt_assert(_n>=2);
/*If _k==0, the following do-while loop will overflow the buffer.*/
celt_assert(_k>0);
k=2;
do _u[k]=(k<<1)-1;
while(++k<len);
for(k=2;k<_n;k++)unext(_u+1,_k+1,1);
}
else{
celt_uint32_t um1;
celt_uint32_t n2m1;
_u[2]=n2m1=um1=(_n<<1)-1;
for(k=3;k<len;k++){
/*U(N,K) = ((2*N-1)*U(N,K-1)-U(N,K-2))/(K-1) + U(N,K-2)*/
_u[k]=um2=imusdiv32even(n2m1,um1,um2,k-1)+um2;
if(++k>=len)break;
_u[k]=um1=imusdiv32odd(n2m1,um2,um1,k-1>>1)+um1;
}
}
return _u[_k]+_u[_k+1];
}
/*Returns the _i'th combination of _k elements (at most 32767) chosen from a
set of size 1 with associated sign bits.
_y: Returns the vector of pulses.*/
static FMOD_INLINE void cwrsi1(int _k,celt_uint32_t _i,int *_y){
int s;
s=-(int)_i;
_y[0]=_k+s^s;
}
/*Returns the _i'th combination of _k elements (at most 32767) chosen from a
set of size 2 with associated sign bits.
_y: Returns the vector of pulses.*/
static FMOD_INLINE void cwrsi2(int _k,celt_uint32_t _i,int *_y){
celt_uint32_t p;
int s;
int yj;
p=ucwrs2(_k+1U);
s=-(_i>=p);
_i-=p&s;
yj=_k;
_k=_i+1>>1;
p=ucwrs2(_k);
_i-=p;
yj-=_k;
_y[0]=yj+s^s;
cwrsi1(_k,_i,_y+1);
}
/*Returns the _i'th combination of _k elements (at most 32767) chosen from a
set of size 3 with associated sign bits.
_y: Returns the vector of pulses.*/
static void cwrsi3(int _k,celt_uint32_t _i,int *_y){
celt_uint32_t p;
int s;
int yj;
p=ucwrs3(_k+1U);
s=-(_i>=p);
_i-=p&s;
yj=_k;
/*Finds the maximum _k such that ucwrs3(_k)<=_i (tested for all
_i<2147418113=U(3,32768)).*/
_k=_i>0?isqrt32(2*_i-1)+1>>1:0;
p=ucwrs3(_k);
_i-=p;
yj-=_k;
_y[0]=yj+s^s;
cwrsi2(_k,_i,_y+1);
}
/*Returns the _i'th combination of _k elements (at most 1172) chosen from a set
of size 4 with associated sign bits.
_y: Returns the vector of pulses.*/
static void cwrsi4(int _k,celt_uint32_t _i,int *_y){
celt_uint32_t p;
int s;
int yj;
int kl;
int kr;
p=ucwrs4(_k+1);
s=-(_i>=p);
_i-=p&s;
yj=_k;
/*We could solve a cubic for k here, but the form of the direct solution does
not lend itself well to exact integer arithmetic.
Instead we do a binary search on U(4,K).*/
kl=0;
kr=_k;
for(;;){
_k=kl+kr>>1;
p=ucwrs4(_k);
if(p<_i){
if(_k>=kr)break;
kl=_k+1;
}
else if(p>_i)kr=_k-1;
else break;
}
_i-=p;
yj-=_k;
_y[0]=yj+s^s;
cwrsi3(_k,_i,_y+1);
}
/*Returns the _i'th combination of _k elements (at most 238) chosen from a set
of size 5 with associated sign bits.
_y: Returns the vector of pulses.*/
static void cwrsi5(int _k,celt_uint32_t _i,int *_y){
celt_uint32_t p;
int s;
int yj;
p=ucwrs5(_k+1);
s=-(_i>=p);
_i-=p&s;
yj=_k;
#if 0
/*Finds the maximum _k such that ucwrs5(_k)<=_i (tested for all
_i<2157192969=U(5,239)).*/
if(_i>=0x2AAAAAA9UL)_k=isqrt32(2*isqrt36(10+6*(celt_uint64_t)_i)-7)+1>>1;
else _k=_i>0?isqrt32(2*(celt_uint32_t)isqrt32(10+6*_i)-7)+1>>1:0;
p=ucwrs5(_k);
#else
/* A binary search on U(5,K) avoids the need for 64-bit arithmetic */
{
int kl=0;
int kr=_k;
for(;;){
_k=kl+kr>>1;
p=ucwrs5(_k);
if(p<_i){
if(_k>=kr)break;
kl=_k+1;
}
else if(p>_i)kr=_k-1;
else break;
}
}
#endif
_i-=p;
yj-=_k;
_y[0]=yj+s^s;
cwrsi4(_k,_i,_y+1);
}
/*Returns the _i'th combination of _k elements chosen from a set of size _n
with associated sign bits.
_y: Returns the vector of pulses.
_u: Must contain entries [0..._k+1] of row _n of U() on input.
Its contents will be destructively modified.*/
static void cwrsi(int _n,int _k,celt_uint32_t _i,int *_y,celt_uint32_t *_u){
int j;
celt_assert(_n>0);
j=0;
do{
celt_uint32_t p;
int s;
int yj;
p=_u[_k+1];
s=-(_i>=p);
_i-=p&s;
yj=_k;
p=_u[_k];
while(p>_i)p=_u[--_k];
_i-=p;
yj-=_k;
_y[j]=yj+s^s;
uprev(_u,_k+2,0);
}
while(++j<_n);
}
/*Returns the index of the given combination of K elements chosen from a set
of size 1 with associated sign bits.
_y: The vector of pulses, whose sum of absolute values is K.
_k: Returns K.*/
static FMOD_INLINE celt_uint32_t icwrs1(const int *_y,int *_k){
*_k=abs(_y[0]);
return _y[0]<0;
}
/*Returns the index of the given combination of K elements chosen from a set
of size 2 with associated sign bits.
_y: The vector of pulses, whose sum of absolute values is K.
_k: Returns K.*/
static FMOD_INLINE celt_uint32_t icwrs2(const int *_y,int *_k){
celt_uint32_t i;
int k;
i=icwrs1(_y+1,&k);
i+=ucwrs2(k);
k+=abs(_y[0]);
if(_y[0]<0)i+=ucwrs2(k+1U);
*_k=k;
return i;
}
/*Returns the index of the given combination of K elements chosen from a set
of size 3 with associated sign bits.
_y: The vector of pulses, whose sum of absolute values is K.
_k: Returns K.*/
static FMOD_INLINE celt_uint32_t icwrs3(const int *_y,int *_k){
celt_uint32_t i;
int k;
i=icwrs2(_y+1,&k);
i+=ucwrs3(k);
k+=abs(_y[0]);
if(_y[0]<0)i+=ucwrs3(k+1U);
*_k=k;
return i;
}
/*Returns the index of the given combination of K elements chosen from a set
of size 4 with associated sign bits.
_y: The vector of pulses, whose sum of absolute values is K.
_k: Returns K.*/
static FMOD_INLINE celt_uint32_t icwrs4(const int *_y,int *_k){
celt_uint32_t i;
int k;
i=icwrs3(_y+1,&k);
i+=ucwrs4(k);
k+=abs(_y[0]);
if(_y[0]<0)i+=ucwrs4(k+1);
*_k=k;
return i;
}
/*Returns the index of the given combination of K elements chosen from a set
of size 5 with associated sign bits.
_y: The vector of pulses, whose sum of absolute values is K.
_k: Returns K.*/
static FMOD_INLINE celt_uint32_t icwrs5(const int *_y,int *_k){
celt_uint32_t i;
int k;
i=icwrs4(_y+1,&k);
i+=ucwrs5(k);
k+=abs(_y[0]);
if(_y[0]<0)i+=ucwrs5(k+1);
*_k=k;
return i;
}
/*Returns the index of the given combination of K elements chosen from a set
of size _n with associated sign bits.
_y: The vector of pulses, whose sum of absolute values must be _k.
_nc: Returns V(_n,_k).*/
celt_uint32_t icwrs(int _n,int _k,celt_uint32_t *_nc,const int *_y,
celt_uint32_t *_u){
celt_uint32_t i;
int j;
int k;
/*We can't unroll the first two iterations of the loop unless _n>=2.*/
celt_assert(_n>=2);
_u[0]=0;
for(k=1;k<=_k+1;k++)_u[k]=(k<<1)-1;
i=icwrs1(_y+_n-1,&k);
j=_n-2;
i+=_u[k];
k+=abs(_y[j]);
if(_y[j]<0)i+=_u[k+1];
while(j-->0){
unext(_u,_k+2,0);
i+=_u[k];
k+=abs(_y[j]);
if(_y[j]<0)i+=_u[k+1];
}
*_nc=_u[k]+_u[k+1];
return i;
}
/*Computes get_required_bits when splitting is required.
_left_bits and _right_bits must contain the required bits for the left and
right sides of the split, respectively (which themselves may require
splitting).*/
static void get_required_split_bits(celt_int16_t *_bits,
const celt_int16_t *_left_bits,const celt_int16_t *_right_bits,
int _n,int _maxk,int _frac){
int k;
for(k=_maxk;k-->0;){
/*If we've reached a k where everything fits in 32 bits, evaluate the
remaining required bits directly.*/
if(fits_in32(_n,k)){
get_required_bits(_bits,_n,k+1,_frac);
break;
}
else{
int worst_bits;
int i;
/*Due to potentially recursive splitting, it's difficult to derive an
analytic expression for the location of the worst-case split index.
We simply check them all.*/
worst_bits=0;
for(i=0;i<=k;i++){
int split_bits;
split_bits=_left_bits[i]+_right_bits[k-i];
if(split_bits>worst_bits)worst_bits=split_bits;
}
_bits[k]=log2_frac(k+1,_frac)+worst_bits;
}
}
}
/*Computes get_required_bits for a pair of N values.
_n1 and _n2 must either be equal or two consecutive integers.
Returns the buffer used to store the required bits for _n2, which is either
_bits1 if _n1==_n2 or _bits2 if _n1+1==_n2.*/
static celt_int16_t *get_required_bits_pair(celt_int16_t *_bits1,
celt_int16_t *_bits2,celt_int16_t *_tmp,int _n1,int _n2,int _maxk,int _frac){
celt_int16_t *tmp2;
/*If we only need a single set of required bits...*/
if(_n1==_n2){
/*Stop recursing if everything fits.*/
if(fits_in32(_n1,_maxk-1))get_required_bits(_bits1,_n1,_maxk,_frac);
else{
_tmp=get_required_bits_pair(_bits2,_tmp,_bits1,
_n1>>1,_n1+1>>1,_maxk,_frac);
get_required_split_bits(_bits1,_bits2,_tmp,_n1,_maxk,_frac);
}
return _bits1;
}
/*Otherwise we need two distinct sets...*/
celt_assert(_n1+1==_n2);
/*Stop recursing if everything fits.*/
if(fits_in32(_n2,_maxk-1)){
get_required_bits(_bits1,_n1,_maxk,_frac);
get_required_bits(_bits2,_n2,_maxk,_frac);
}
/*Otherwise choose an evaluation order that doesn't require extra buffers.*/
else if(_n1&1){
/*This special case isn't really needed, but can save some work.*/
if(fits_in32(_n1,_maxk-1)){
tmp2=get_required_bits_pair(_tmp,_bits1,_bits2,
_n2>>1,_n2>>1,_maxk,_frac);
get_required_split_bits(_bits2,_tmp,tmp2,_n2,_maxk,_frac);
get_required_bits(_bits1,_n1,_maxk,_frac);
}
else{
_tmp=get_required_bits_pair(_bits2,_tmp,_bits1,
_n1>>1,_n1+1>>1,_maxk,_frac);
get_required_split_bits(_bits1,_bits2,_tmp,_n1,_maxk,_frac);
get_required_split_bits(_bits2,_tmp,_tmp,_n2,_maxk,_frac);
}
}
else{
/*There's no need to special case _n1 fitting by itself, since _n2 requires
us to recurse for both values anyway.*/
tmp2=get_required_bits_pair(_tmp,_bits1,_bits2,
_n2>>1,_n2+1>>1,_maxk,_frac);
get_required_split_bits(_bits2,_tmp,tmp2,_n2,_maxk,_frac);
get_required_split_bits(_bits1,_tmp,_tmp,_n1,_maxk,_frac);
}
return _bits2;
}
void get_required_bits(celt_int16_t *_bits,int _n,int _maxk,int _frac){
int k;
/*_maxk==0 => there's nothing to do.*/
celt_assert(_maxk>0);
if(fits_in32(_n,_maxk-1)){
_bits[0]=0;
if(_maxk>1){
VARDECL(celt_uint32_t,u);
SAVE_STACK;
ALLOC(u,_maxk+1U,celt_uint32_t);
ncwrs_urow(_n,_maxk-1,u);
for(k=1;k<_maxk;k++)_bits[k]=log2_frac(u[k]+u[k+1],_frac);
RESTORE_STACK;
}
}
else{
VARDECL(celt_int16_t,n1bits);
VARDECL(celt_int16_t,n2bits_buf);
celt_int16_t *n2bits;
SAVE_STACK;
ALLOC(n1bits,_maxk,celt_int16_t);
ALLOC(n2bits_buf,_maxk,celt_int16_t);
n2bits=get_required_bits_pair(n1bits,n2bits_buf,_bits,
_n>>1,_n+1>>1,_maxk,_frac);
get_required_split_bits(_bits,n1bits,n2bits,_n,_maxk,_frac);
RESTORE_STACK;
}
}
#ifdef FMOD_CELT_ENCODER
static FMOD_INLINE void encode_pulses32(int _n,int _k,const int *_y,ec_enc *_enc){
celt_uint32_t i;
switch(_n){
case 1:{
i=icwrs1(_y,&_k);
celt_assert(ncwrs1(_k)==2);
ec_enc_bits(_enc,i,1);
}break;
case 2:{
i=icwrs2(_y,&_k);
ec_enc_uint(_enc,i,ncwrs2(_k));
}break;
case 3:{
i=icwrs3(_y,&_k);
ec_enc_uint(_enc,i,ncwrs3(_k));
}break;
case 4:{
i=icwrs4(_y,&_k);
ec_enc_uint(_enc,i,ncwrs4(_k));
}break;
case 5:{
i=icwrs5(_y,&_k);
ec_enc_uint(_enc,i,ncwrs5(_k));
}break;
default:{
VARDECL(celt_uint32_t,u);
celt_uint32_t nc;
SAVE_STACK;
ALLOC(u,_k+2U,celt_uint32_t);
i=icwrs(_n,_k,&nc,_y,u);
ec_enc_uint(_enc,i,nc);
RESTORE_STACK;
}break;
}
}
void encode_pulses(int *_y, int N, int K, ec_enc *enc)
{
if (K==0) {
} else if(fits_in32(N,K))
{
encode_pulses32(N, K, _y, enc);
} else {
int i;
int count=0;
int split;
split = (N+1)/2;
for (i=0;i<split;i++)
count += abs(_y[i]);
ec_enc_uint(enc,count,K+1);
encode_pulses(_y, split, count, enc);
encode_pulses(_y+split, N-split, K-count, enc);
}
}
#endif
static FMOD_INLINE void decode_pulses32(int _n,int _k,int *_y,ec_dec *_dec){
switch(_n){
case 1:{
celt_assert(ncwrs1(_k)==2);
cwrsi1(_k,ec_dec_bits(_dec,1),_y);
}break;
case 2:cwrsi2(_k,ec_dec_uint(_dec,ncwrs2(_k)),_y);break;
case 3:cwrsi3(_k,ec_dec_uint(_dec,ncwrs3(_k)),_y);break;
case 4:cwrsi4(_k,ec_dec_uint(_dec,ncwrs4(_k)),_y);break;
case 5:cwrsi5(_k,ec_dec_uint(_dec,ncwrs5(_k)),_y);break;
default:{
VARDECL(celt_uint32_t,u);
SAVE_STACK;
ALLOC(u,_k+2U,celt_uint32_t);
cwrsi(_n,_k,ec_dec_uint(_dec,ncwrs_urow(_n,_k,u)),_y,u);
RESTORE_STACK;
}
}
}
void decode_pulses(int *_y, int N, int K, ec_dec *dec)
{
if (K==0) {
int i;
for (i=0;i<N;i++)
_y[i] = 0;
} else if(fits_in32(N,K))
{
decode_pulses32(N, K, _y, dec);
} else {
int split;
int count = ec_dec_uint(dec,K+1);
split = (N+1)/2;
decode_pulses(_y, split, count, dec);
decode_pulses(_y+split, N-split, K-count, dec);
}
}

50
fmod/lib/libcelt/cwrs.h Executable file
View file

@ -0,0 +1,50 @@
/* (C) 2007-2008 Timothy Terriberry */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CWRS_H
#define CWRS_H
#include "arch.h"
#include "stack_alloc.h"
#include "entenc.h"
#include "entdec.h"
int log2_frac(ec_uint32 val, int frac);
/* Whether the CWRS codebook will fit into 32 bits */
int fits_in32(int _n, int _m);
void get_required_bits(celt_int16_t *bits, int N, int K, int frac);
void encode_pulses(int *_y, int N, int K, ec_enc *enc);
void decode_pulses(int *_y, int N, int K, ec_dec *dec);
#endif /* CWRS_H */

136
fmod/lib/libcelt/ecintrin.h Executable file
View file

@ -0,0 +1,136 @@
/* (C) 2003-2008 Timothy B. Terriberry
(C) 2008 Jean-Marc Valin */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*Some common macros for potential platform-specific optimization.*/
#include <math.h>
#include <limits.h>
#if !defined(_ecintrin_H)
# define _ecintrin_H (1)
/*Some specific platforms may have optimized intrinsic or inline assembly
versions of these functions which can substantially improve performance.
We define macros for them to allow easy incorporation of these non-ANSI
features.*/
/*Note that we do not provide a macro for abs(), because it is provided as a
library function, which we assume is translated into an intrinsic to avoid
the function call overhead and then implemented in the smartest way for the
target platform.
With modern gcc (4.x), this is true: it uses cmov instructions if the
architecture supports it and branchless bit-twiddling if it does not (the
speed difference between the two approaches is not measurable).
Interestingly, the bit-twiddling method was patented in 2000 (US 6,073,150)
by Sun Microsystems, despite prior art dating back to at least 1996:
http://web.archive.org/web/19961201174141/www.x86.org/ftp/articles/pentopt/PENTOPT.TXT
On gcc 3.x, however, our assumption is not true, as abs() is translated to a
conditional jump, which is horrible on deeply piplined architectures (e.g.,
all consumer architectures for the past decade or more) when the sign cannot
be reliably predicted.*/
/*Modern gcc (4.x) can compile the naive versions of min and max with cmov if
given an appropriate architecture, but the branchless bit-twiddling versions
are just as fast, and do not require any special target architecture.
Earlier gcc versions (3.x) compiled both code to the same assembly
instructions, because of the way they represented ((_b)>(_a)) internally.*/
#define EC_MAXI(_a,_b) ((_a)-((_a)-(_b)&-((_b)>(_a))))
#define EC_MINI(_a,_b) ((_a)+((_b)-(_a)&-((_b)<(_a))))
/*This has a chance of compiling branchless, and is just as fast as the
bit-twiddling method, which is slightly less portable, since it relies on a
sign-extended rightshift, which is not guaranteed by ANSI (but present on
every relevant platform).*/
#define EC_SIGNI(_a) (((_a)>0)-((_a)<0))
/*Slightly more portable than relying on a sign-extended right-shift (which is
not guaranteed by ANSI), and just as fast, since gcc (3.x and 4.x both)
compile it into the right-shift anyway.*/
#define EC_SIGNMASK(_a) (-((_a)<0))
/*Clamps an integer into the given range.
If _a>_c, then the lower bound _a is respected over the upper bound _c (this
behavior is required to meet our documented API behavior).
_a: The lower bound.
_b: The value to clamp.
_c: The upper boud.*/
#define EC_CLAMPI(_a,_b,_c) (EC_MAXI(_a,EC_MINI(_b,_c)))
/*Count leading zeros.
This macro should only be used for implementing ec_ilog(), if it is defined.
All other code should use EC_ILOG() instead.*/
#ifdef __GNUC_PREREQ
#if __GNUC_PREREQ(3,4)
# if INT_MAX>=2147483647
# define EC_CLZ0 sizeof(unsigned)*CHAR_BIT
# define EC_CLZ(_x) (__builtin_clz(_x))
# elif LONG_MAX>=2147483647L
# define EC_CLZ0 sizeof(unsigned long)*CHAR_BIT
# define EC_CLZ(_x) (__builtin_clzl(_x))
# endif
#endif
#endif
#if defined(EC_CLZ)
/*Note that __builtin_clz is not defined when _x==0, according to the gcc
documentation (and that of the BSR instruction that implements it on x86).
The majority of the time we can never pass it zero.
When we need to, it can be special cased.*/
# define EC_ILOG(_x) (EC_CLZ0-EC_CLZ(_x))
#elif defined(ENABLE_TI_DSPLIB)
#include "dsplib.h"
#define EC_ILOG(x) (31 - _lnorm(x))
#else
# define EC_ILOG(_x) (ec_ilog(_x))
#endif
#ifdef __GNUC_PREREQ
#if __GNUC_PREREQ(3,4)
# if INT_MAX>=9223372036854775807
# define EC_CLZ64_0 sizeof(unsigned)*CHAR_BIT
# define EC_CLZ64(_x) (__builtin_clz(_x))
# elif LONG_MAX>=9223372036854775807L
# define EC_CLZ64_0 sizeof(unsigned long)*CHAR_BIT
# define EC_CLZ64(_x) (__builtin_clzl(_x))
# elif LLONG_MAX>=9223372036854775807LL
# define EC_CLZ64_0 sizeof(unsigned long long)*CHAR_BIT
# define EC_CLZ64(_x) (__builtin_clzll(_x))
# endif
#endif
#endif
#if defined(EC_CLZ64)
/*Note that __builtin_clz is not defined when _x==0, according to the gcc
documentation (and that of the BSR instruction that implements it on x86).
The majority of the time we can never pass it zero.
When we need to, it can be special cased.*/
# define EC_ILOG64(_x) (EC_CLZ64_0-EC_CLZ64(_x))
#else
# define EC_ILOG64(_x) (ec_ilog64(_x))
#endif
#endif

70
fmod/lib/libcelt/entcode.c Executable file
View file

@ -0,0 +1,70 @@
/* (C) 2001-2008 Timothy B. Terriberry
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "entcode.h"
int ec_ilog(ec_uint32 _v){
#if defined(EC_CLZ)
return EC_CLZ0-EC_CLZ(_v);
#else
/*On a Pentium M, this branchless version tested as the fastest on
1,000,000,000 random 32-bit integers, edging out a similar version with
branches, and a 256-entry LUT version.*/
int ret;
int m;
ret=!!_v;
m=!!(_v&0xFFFF0000)<<4;
_v>>=m;
ret|=m;
m=!!(_v&0xFF00)<<3;
_v>>=m;
ret|=m;
m=!!(_v&0xF0)<<2;
_v>>=m;
ret|=m;
m=!!(_v&0xC)<<1;
_v>>=m;
ret|=m;
ret+=!!(_v&0x2);
return ret;
#endif
}

95
fmod/lib/libcelt/entcode.h Executable file
View file

@ -0,0 +1,95 @@
/* (C) 2001-2008 Timothy B. Terriberry
(C) 2008 Jean-Marc Valin */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "celt_types.h"
#if !defined(_entcode_H)
# define _entcode_H (1)
# include <limits.h>
# include "ecintrin.h"
typedef celt_int32_t ec_int32;
typedef celt_uint32_t ec_uint32;
typedef celt_uint64_t ec_uint64;
typedef struct ec_byte_buffer ec_byte_buffer;
/*The number of bits to code at a time when coding bits directly.*/
# define EC_UNIT_BITS (8)
/*The mask for the given bits.*/
# define EC_UNIT_MASK ((1U<<EC_UNIT_BITS)-1)
/*Simple libogg1-style buffer.*/
struct ec_byte_buffer{
unsigned char *buf;
unsigned char *ptr;
long storage;
int resizable;
};
/*Encoding functions.*/
void ec_byte_writeinit_buffer(ec_byte_buffer *_b, unsigned char *_buf, long _size);
void ec_byte_writeinit(ec_byte_buffer *_b);
void ec_byte_writetrunc(ec_byte_buffer *_b,long _bytes);
void ec_byte_write1(ec_byte_buffer *_b,unsigned _value);
void ec_byte_write4(ec_byte_buffer *_b,ec_uint32 _value);
void ec_byte_writecopy(ec_byte_buffer *_b,void *_source,long _bytes);
void ec_byte_writeclear(ec_byte_buffer *_b);
/*Decoding functions.*/
void ec_byte_readinit(ec_byte_buffer *_b,unsigned char *_buf,long _bytes);
int ec_byte_look1(ec_byte_buffer *_b);
int ec_byte_look4(ec_byte_buffer *_b,ec_uint32 *_val);
void ec_byte_adv1(ec_byte_buffer *_b);
void ec_byte_adv4(ec_byte_buffer *_b);
int ec_byte_read1(ec_byte_buffer *_b);
int ec_byte_read4(ec_byte_buffer *_b,ec_uint32 *_val);
/*Shared functions.*/
static FMOD_INLINE void ec_byte_reset(ec_byte_buffer *_b){
_b->ptr=_b->buf;
}
static FMOD_INLINE long ec_byte_bytes(ec_byte_buffer *_b){
return _b->ptr-_b->buf;
}
static FMOD_INLINE unsigned char *ec_byte_get_buffer(ec_byte_buffer *_b){
return _b->buf;
}
int ec_ilog(ec_uint32 _v);
int ec_ilog64(ec_uint64 _v);
#endif

165
fmod/lib/libcelt/entdec.c Executable file
View file

@ -0,0 +1,165 @@
/* (C) 2001-2008 Timothy B. Terriberry
(C) 2008 Jean-Marc Valin */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stddef.h>
#include "entdec.h"
#include "os_support.h"
#include "arch.h"
void ec_byte_readinit(ec_byte_buffer *_b,unsigned char *_buf,long _bytes){
_b->buf=_b->ptr=_buf;
_b->storage=_bytes;
}
int ec_byte_look1(ec_byte_buffer *_b){
ptrdiff_t endbyte;
endbyte=_b->ptr-_b->buf;
if(endbyte>=_b->storage)return -1;
else return _b->ptr[0];
}
int ec_byte_look4(ec_byte_buffer *_b,ec_uint32 *_val){
ptrdiff_t endbyte;
endbyte=_b->ptr-_b->buf;
if(endbyte+4>_b->storage){
if(endbyte<_b->storage){
*_val=_b->ptr[0];
endbyte++;
if(endbyte<_b->storage){
*_val|=(ec_uint32)_b->ptr[1]<<8;
endbyte++;
if(endbyte<_b->storage)*_val|=(ec_uint32)_b->ptr[2]<<16;
}
}
return -1;
}
else{
*_val=_b->ptr[0];
*_val|=(ec_uint32)_b->ptr[1]<<8;
*_val|=(ec_uint32)_b->ptr[2]<<16;
*_val|=(ec_uint32)_b->ptr[3]<<24;
}
return 0;
}
void ec_byte_adv1(ec_byte_buffer *_b){
_b->ptr++;
}
void ec_byte_adv4(ec_byte_buffer *_b){
_b->ptr+=4;
}
int ec_byte_read1(ec_byte_buffer *_b){
ptrdiff_t endbyte;
endbyte=_b->ptr-_b->buf;
if(endbyte>=_b->storage)return -1;
else return *(_b->ptr++);
}
int ec_byte_read4(ec_byte_buffer *_b,ec_uint32 *_val){
unsigned char *end;
end=_b->buf+_b->storage;
if(_b->ptr+4>end){
if(_b->ptr<end){
*_val=*(_b->ptr++);
if(_b->ptr<end){
*_val|=(ec_uint32)*(_b->ptr++)<<8;
if(_b->ptr<end)*_val|=(ec_uint32)*(_b->ptr++)<<16;
}
}
return -1;
}
else{
*_val=(*_b->ptr++);
*_val|=(ec_uint32)*(_b->ptr++)<<8;
*_val|=(ec_uint32)*(_b->ptr++)<<16;
*_val|=(ec_uint32)*(_b->ptr++)<<24;
}
return 0;
}
ec_uint32 ec_dec_bits(ec_dec *_this,int _ftb){
ec_uint32 t;
unsigned s;
unsigned ft;
t=0;
while(_ftb>EC_UNIT_BITS){
s=ec_decode_bin(_this,EC_UNIT_BITS);
ec_dec_update(_this,s,s+1,EC_UNIT_MASK+1);
t=t<<EC_UNIT_BITS|s;
_ftb-=EC_UNIT_BITS;
}
ft=1U<<_ftb;
s=ec_decode_bin(_this,_ftb);
ec_dec_update(_this,s,s+1,ft);
t=t<<_ftb|s;
return t;
}
ec_uint32 ec_dec_uint(ec_dec *_this,ec_uint32 _ft){
ec_uint32 t;
unsigned ft;
unsigned s;
int ftb;
t=0;
/*In order to optimize EC_ILOG(), it is undefined for the value 0.*/
celt_assert(_ft>1);
_ft--;
ftb=EC_ILOG(_ft);
if(ftb>EC_UNIT_BITS){
ftb-=EC_UNIT_BITS;
ft=(unsigned)(_ft>>ftb)+1;
s=ec_decode(_this,ft);
ec_dec_update(_this,s,s+1,ft);
t=t<<EC_UNIT_BITS|s;
t = t<<ftb|ec_dec_bits(_this,ftb);
if (t>_ft)
{
celt_notify("uint decode error");
t = _ft;
}
return t;
} else {
_ft++;
s=ec_decode(_this,(unsigned)_ft);
ec_dec_update(_this,s,s+1,(unsigned)_ft);
t=t<<ftb|s;
return t;
}
}

134
fmod/lib/libcelt/entdec.h Executable file
View file

@ -0,0 +1,134 @@
/* (C) 2001-2008 Timothy B. Terriberry
(C) 2008 Jean-Marc Valin */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if !defined(_entdec_H)
# define _entdec_H (1)
# include "entcode.h"
typedef struct ec_dec ec_dec;
/*The entropy decoder.*/
struct ec_dec{
/*The buffer to decode.*/
ec_byte_buffer *buf;
/*The remainder of a buffered input symbol.*/
int rem;
/*The number of values in the current range.*/
ec_uint32 rng;
/*The difference between the input value and the lowest value in the current
range.*/
ec_uint32 dif;
/*Normalization factor.*/
ec_uint32 nrm;
};
/*Initializes the decoder.
_buf: The input buffer to use.
Return: 0 on success, or a negative value on error.*/
void ec_dec_init(ec_dec *_this,ec_byte_buffer *_buf);
/*Calculates the cumulative frequency for the next symbol.
This can then be fed into the probability model to determine what that
symbol is, and the additional frequency information required to advance to
the next symbol.
This function cannot be called more than once without a corresponding call to
ec_dec_update(), or decoding will not proceed correctly.
_ft: The total frequency of the symbols in the alphabet the next symbol was
encoded with.
Return: A cumulative frequency representing the encoded symbol.
If the cumulative frequency of all the symbols before the one that
was encoded was fl, and the cumulative frequency of all the symbols
up to and including the one encoded is fh, then the returned value
will fall in the range [fl,fh).*/
unsigned ec_decode(ec_dec *_this,unsigned _ft);
unsigned ec_decode_bin(ec_dec *_this,unsigned bits);
/*Advance the decoder past the next symbol using the frequency information the
symbol was encoded with.
Exactly one call to ec_decode() must have been made so that all necessary
intermediate calculations are performed.
_fl: The cumulative frequency of all symbols that come before the symbol
decoded.
_fh: The cumulative frequency of all symbols up to and including the symbol
decoded.
Together with _fl, this defines the range [_fl,_fh) in which the value
returned above must fall.
_ft: The total frequency of the symbols in the alphabet the symbol decoded
was encoded in.
This must be the same as passed to the preceding call to ec_decode().*/
void ec_dec_update(ec_dec *_this,unsigned _fl,unsigned _fh,
unsigned _ft);
/*Extracts a sequence of raw bits from the stream.
The bits must have been encoded with ec_enc_bits().
No call to ec_dec_update() is necessary after this call.
_ftb: The number of bits to extract.
This must be at least one, and no more than 32.
Return: The decoded bits.*/
ec_uint32 ec_dec_bits(ec_dec *_this,int _ftb);
/*Extracts a sequence of raw bits from the stream.
The bits must have been encoded with ec_enc_bits64().
No call to ec_dec_update() is necessary after this call.
_ftb: The number of bits to extract.
This must be at least one, and no more than 64.
Return: The decoded bits.*/
ec_uint64 ec_dec_bits64(ec_dec *_this,int _ftb);
/*Extracts a raw unsigned integer with a non-power-of-2 range from the stream.
The bits must have been encoded with ec_enc_uint().
No call to ec_dec_update() is necessary after this call.
_ft: The number of integers that can be decoded (one more than the max).
This must be at least one, and no more than 2**32-1.
Return: The decoded bits.*/
ec_uint32 ec_dec_uint(ec_dec *_this,ec_uint32 _ft);
/*Extracts a raw unsigned integer with a non-power-of-2 range from the stream.
The bits must have been encoded with ec_enc_uint64().
No call to ec_dec_update() is necessary after this call.
_ft: The number of integers that can be decoded (one more than the max).
This must be at least one, and no more than 2**64-1.
Return: The decoded bits.*/
ec_uint64 ec_dec_uint64(ec_dec *_this,ec_uint64 _ft);
/*Returns the number of bits "used" by the decoded symbols so far.
The actual number of bits may be larger, due to rounding to whole bytes, or
smaller, due to trailing zeros that were be stripped, so this is not an
estimate of the true packet size.
This same number can be computed by the encoder, and is suitable for making
coding decisions.
_b: The number of extra bits of precision to include.
At most 16 will be accurate.
Return: The number of bits scaled by 2**_b.
This will always be slightly larger than the exact value (e.g., all
rounding error is in the positive direction).*/
long ec_dec_tell(ec_dec *_this,int _b);
#endif

151
fmod/lib/libcelt/entenc.c Executable file
View file

@ -0,0 +1,151 @@
/* (C) 2001-2008 Timothy B. Terriberry
(C) 2008 Jean-Marc Valin */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef FMOD_CELT_ENCODER
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "os_support.h"
#include "entenc.h"
#include "arch.h"
#define EC_BUFFER_INCREMENT (256)
void ec_byte_writeinit_buffer(ec_byte_buffer *_b, unsigned char *_buf, long _size){
_b->ptr=_b->buf=_buf;
_b->storage=_size;
_b->resizable = 0;
}
void ec_byte_writeinit(ec_byte_buffer *_b){
_b->ptr=_b->buf=celt_alloc(EC_BUFFER_INCREMENT*sizeof(char));
_b->storage=EC_BUFFER_INCREMENT;
_b->resizable = 1;
}
void ec_byte_writetrunc(ec_byte_buffer *_b,long _bytes){
_b->ptr=_b->buf+_bytes;
}
void ec_byte_write1(ec_byte_buffer *_b,unsigned _value){
ptrdiff_t endbyte;
endbyte=_b->ptr-_b->buf;
if(endbyte>=_b->storage){
if (_b->resizable){
_b->buf=celt_realloc(_b->buf,(_b->storage+EC_BUFFER_INCREMENT)*sizeof(char));
_b->storage+=EC_BUFFER_INCREMENT;
_b->ptr=_b->buf+endbyte;
} else {
celt_fatal("range encoder overflow\n");
}
}
*(_b->ptr++)=(unsigned char)_value;
}
void ec_byte_write4(ec_byte_buffer *_b,ec_uint32 _value){
ptrdiff_t endbyte;
endbyte=_b->ptr-_b->buf;
if(endbyte+4>_b->storage){
if (_b->resizable){
_b->buf=celt_realloc(_b->buf,(_b->storage+EC_BUFFER_INCREMENT)*sizeof(char));
_b->storage+=EC_BUFFER_INCREMENT;
_b->ptr=_b->buf+endbyte;
} else {
celt_fatal("range encoder overflow\n");
}
}
*(_b->ptr++)=(unsigned char)_value;
_value>>=8;
*(_b->ptr++)=(unsigned char)_value;
_value>>=8;
*(_b->ptr++)=(unsigned char)_value;
_value>>=8;
*(_b->ptr++)=(unsigned char)_value;
}
void ec_byte_writecopy(ec_byte_buffer *_b,void *_source,long _bytes){
ptrdiff_t endbyte;
endbyte=_b->ptr-_b->buf;
if(endbyte+_bytes>_b->storage){
if (_b->resizable){
_b->storage=endbyte+_bytes+EC_BUFFER_INCREMENT;
_b->buf=celt_realloc(_b->buf,_b->storage*sizeof(char));
_b->ptr=_b->buf+endbyte;
} else {
celt_fatal("range encoder overflow\n");
}
}
memmove(_b->ptr,_source,_bytes);
_b->ptr+=_bytes;
}
void ec_byte_writeclear(ec_byte_buffer *_b){
celt_free(_b->buf);
}
void ec_enc_bits(ec_enc *_this,ec_uint32 _fl,int _ftb){
unsigned fl;
unsigned ft;
while(_ftb>EC_UNIT_BITS){
_ftb-=EC_UNIT_BITS;
fl=(unsigned)(_fl>>_ftb)&EC_UNIT_MASK;
ec_encode_bin(_this,fl,fl+1,EC_UNIT_BITS);
}
ft=1<<_ftb;
fl=(unsigned)_fl&ft-1;
ec_encode_bin(_this,fl,fl+1,_ftb);
}
void ec_enc_uint(ec_enc *_this,ec_uint32 _fl,ec_uint32 _ft){
unsigned ft;
unsigned fl;
int ftb;
/*In order to optimize EC_ILOG(), it is undefined for the value 0.*/
celt_assert(_ft>1);
_ft--;
ftb=EC_ILOG(_ft);
if(ftb>EC_UNIT_BITS){
ftb-=EC_UNIT_BITS;
ft=(_ft>>ftb)+1;
fl=(unsigned)(_fl>>ftb);
ec_encode(_this,fl,fl+1,ft);
ec_enc_bits(_this,_fl,ftb);
} else {
ec_encode(_this,_fl,_fl+1,_ft+1);
}
}
#endif

116
fmod/lib/libcelt/entenc.h Executable file
View file

@ -0,0 +1,116 @@
/* (C) 2001-2008 Timothy B. Terriberry
(C) 2008 Jean-Marc Valin */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if !defined(_entenc_H)
# define _entenc_H (1)
# include <stddef.h>
# include "entcode.h"
typedef struct ec_enc ec_enc;
/*The entropy encoder.*/
struct ec_enc{
/*Buffered output.*/
ec_byte_buffer *buf;
/*A buffered output symbol, awaiting carry propagation.*/
int rem;
/*Number of extra carry propagating symbols.*/
size_t ext;
/*The number of values in the current range.*/
ec_uint32 rng;
/*The low end of the current range (inclusive).*/
ec_uint32 low;
};
/*Initializes the encoder.
_buf: The buffer to store output bytes in.
This must have already been initialized for writing and reset.*/
void ec_enc_init(ec_enc *_this,ec_byte_buffer *_buf);
/*Encodes a symbol given its frequency information.
The frequency information must be discernable by the decoder, assuming it
has read only the previous symbols from the stream.
It is allowable to change the frequency information, or even the entire
source alphabet, so long as the decoder can tell from the context of the
previously encoded information that it is supposed to do so as well.
_fl: The cumulative frequency of all symbols that come before the one to be
encoded.
_fh: The cumulative frequency of all symbols up to and including the one to
be encoded.
Together with _fl, this defines the range [_fl,_fh) in which the
decoded value will fall.
_ft: The sum of the frequencies of all the symbols*/
void ec_encode(ec_enc *_this,unsigned _fl,unsigned _fh,unsigned _ft);
void ec_encode_bin(ec_enc *_this,unsigned _fl,unsigned _fh,unsigned bits);
/*Encodes a sequence of raw bits in the stream.
_fl: The bits to encode.
_ftb: The number of bits to encode.
This must be at least one, and no more than 32.*/
void ec_enc_bits(ec_enc *_this,ec_uint32 _fl,int _ftb);
/*Encodes a sequence of raw bits in the stream.
_fl: The bits to encode.
_ftb: The number of bits to encode.
This must be at least one, and no more than 64.*/
void ec_enc_bits64(ec_enc *_this,ec_uint64 _fl,int _ftb);
/*Encodes a raw unsigned integer in the stream.
_fl: The integer to encode.
_ft: The number of integers that can be encoded (one more than the max).
This must be at least one, and no more than 2**32-1.*/
void ec_enc_uint(ec_enc *_this,ec_uint32 _fl,ec_uint32 _ft);
/*Encodes a raw unsigned integer in the stream.
_fl: The integer to encode.
_ft: The number of integers that can be encoded (one more than the max).
This must be at least one, and no more than 2**64-1.*/
void ec_enc_uint64(ec_enc *_this,ec_uint64 _fl,ec_uint64 _ft);
/*Returns the number of bits "used" by the encoded symbols so far.
The actual number of bits may be larger, due to rounding to whole bytes, or
smaller, due to trailing zeros that can be stripped, so this is not an
estimate of the true packet size.
This same number can be computed by the decoder, and is suitable for making
coding decisions.
_b: The number of extra bits of precision to include.
At most 16 will be accurate.
Return: The number of bits scaled by 2**_b.
This will always be slightly larger than the exact value (e.g., all
rounding error is in the positive direction).*/
long ec_enc_tell(ec_enc *_this,int _b);
/*Indicates that there are no more symbols to encode.
All reamining output bytes are flushed to the output buffer.
ec_enc_init() must be called before the encoder can be used again.*/
void ec_enc_done(ec_enc *_this);
#endif

93
fmod/lib/libcelt/fixed_c5x.h Executable file
View file

@ -0,0 +1,93 @@
/* Copyright (C) 2003 Jean-Marc Valin */
/**
@file fixed_c5x.h
@brief Fixed-point operations for the TI C5x DSP family
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef FIXED_C5X_H
#define FIXED_C5X_H
#include "dsplib.h"
#undef IMUL32
static inline long IMUL32(long i, long j)
{
long ac0, ac1;
ac0 = _lmpy(i>>16,j);
ac1 = ac0 + _lmpy(i,j>>16);
return _lmpyu(i,j) + (ac1<<16);
}
#undef MAX16
#define MAX16(a,b) _max(a,b)
#undef MIN16
#define MIN16(a,b) _min(a,b)
#undef MAX32
#define MAX32(a,b) _lmax(a,b)
#undef MIN32
#define MIN32(a,b) _lmin(a,b)
#undef VSHR32
#define VSHR32(a, shift) _lshl(a,-(shift))
#undef MULT16_16_Q15
#define MULT16_16_Q15(a,b) (_smpy(a,b))
#undef MULT16_16SU
#define MULT16_16SU(a,b) _lmpysu(a,b)
#undef MULT_16_16
#define MULT_16_16(a,b) _lmpy(a,b)
/* FIXME: This is technically incorrect and is bound to cause problems. Is there any cleaner solution? */
#undef MULT16_32_Q15
#define MULT16_32_Q15(a,b) ADD32(SHL(MULT16_16((a),SHR((b),16)),1), SHR(MULT16_16SU((a),(b)),15))
#define celt_ilog2(x) (30 - _lnorm(x))
#define OVERRIDE_CELT_ILOG2
#define celt_maxabs16(x, len) MAX16(maxval((DATA *)x, len),-minval((DATA *)x, len))
#define OVERRIDE_CELT_MAXABS16
#define OVERRIDE_FIND_MAX16
static inline int find_max16(celt_word16_t *x, int len)
{
DATA max_corr16 = -VERY_LARGE16;
DATA pitch16 = 0;
maxvec((DATA *)x, len, &max_corr16, &pitch16);
return pitch16;
}
#endif /* FIXED_C5X_H */

84
fmod/lib/libcelt/fixed_c6x.h Executable file
View file

@ -0,0 +1,84 @@
/* Copyright (C) 2008 CSIRO */
/**
@file fixed_c6x.h
@brief Fixed-point operations for the TI C6x DSP family
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef FIXED_C6X_H
#define FIXED_C6X_H
#undef MULT16_16SU
#define MULT16_16SU(a,b) _mpysu(a,b)
#undef MULT_16_16
#define MULT_16_16(a,b) _mpy(a,b)
#define celt_ilog2(x) (30 - _norm(x))
#define OVERRIDE_CELT_ILOG2
#undef MULT16_32_Q15
#define MULT16_32_Q15(a,b) ADD32(SHL(_mpylh(a,b),1), SHR(_mpsu(a,b),15)
#if 0
#include "dsplib.h"
#undef MAX16
#define MAX16(a,b) _max(a,b)
#undef MIN16
#define MIN16(a,b) _min(a,b)
#undef MAX32
#define MAX32(a,b) _lmax(a,b)
#undef MIN32
#define MIN32(a,b) _lmin(a,b)
#undef VSHR32
#define VSHR32(a, shift) _lshl(a,-(shift))
#undef MULT16_16_Q15
#define MULT16_16_Q15(a,b) (_smpy(a,b))
#define celt_maxabs16(x, len) MAX16(maxval((DATA *)x, len),-minval((DATA *)x, len))
#define OVERRIDE_CELT_MAXABS16
#define OVERRIDE_FIND_MAX16
static inline int find_max16(celt_word16_t *x, int len)
{
DATA max_corr16 = -VERY_LARGE16;
DATA pitch16 = 0;
maxvec((DATA *)x, len, &max_corr16, &pitch16);
return pitch16;
}
#endif
#endif /* FIXED_C6X_H */

159
fmod/lib/libcelt/fixed_generic.h Executable file
View file

@ -0,0 +1,159 @@
/* Copyright (C) 2003-2008 Jean-Marc Valin, CSIRO */
/**
@file fixed_generic.h
@brief Generic fixed-point operations
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef FIXED_GENERIC_H
#define FIXED_GENERIC_H
/** Multiply a 16-bit signed value by a 16-bit unsigned value. The result is a 32-bit signed value */
#define MULT16_16SU(a,b) ((celt_word32_t)(celt_word16_t)(a)*(celt_word32_t)(celt_uint16_t)(b))
/** 16x32 multiplication, followed by a 16-bit shift right. Results fits in 32 bits */
#define MULT16_32_Q16(a,b) ADD32(MULT16_16((a),SHR((b),16)), SHR(MULT16_16SU((a),((b)&0x0000ffff)),16))
/** 16x32 multiplication, followed by a 15-bit shift right. Results fits in 32 bits */
#define MULT16_32_Q15(a,b) ADD32(SHL(MULT16_16((a),SHR((b),16)),1), SHR(MULT16_16SU((a),((b)&0x0000ffff)),15))
/** 32x32 multiplication, followed by a 31-bit shift right. Results fits in 32 bits */
#define MULT32_32_Q31(a,b) ADD32(ADD32(SHL(MULT16_16(SHR((a),16),SHR((b),16)),1), SHR(MULT16_16SU(SHR((a),16),((b)&0x0000ffff)),15)), SHR(MULT16_16SU(SHR((b),16),((a)&0x0000ffff)),15))
/** 32x32 multiplication, followed by a 32-bit shift right. Results fits in 32 bits */
#define MULT32_32_Q32(a,b) ADD32(ADD32(MULT16_16(SHR((a),16),SHR((b),16)), SHR(MULT16_16SU(SHR((a),16),((b)&0x0000ffff)),16)), SHR(MULT16_16SU(SHR((b),16),((a)&0x0000ffff)),16))
/** Compile-time conversion of float constant to 16-bit value */
#define QCONST16(x,bits) ((celt_word16_t)(.5+(x)*(((celt_word32_t)1)<<(bits))))
/** Compile-time conversion of float constant to 32-bit value */
#define QCONST32(x,bits) ((celt_word32_t)(.5+(x)*(((celt_word32_t)1)<<(bits))))
/** Negate a 16-bit value */
#define NEG16(x) (-(x))
/** Negate a 32-bit value */
#define NEG32(x) (-(x))
/** Change a 32-bit value into a 16-bit value. The value is assumed to fit in 16-bit, otherwise the result is undefined */
#define EXTRACT16(x) ((celt_word16_t)(x))
/** Change a 16-bit value into a 32-bit value */
#define EXTEND32(x) ((celt_word32_t)(x))
/** Arithmetic shift-right of a 16-bit value */
#define SHR16(a,shift) ((a) >> (shift))
/** Arithmetic shift-left of a 16-bit value */
#define SHL16(a,shift) ((a) << (shift))
/** Arithmetic shift-right of a 32-bit value */
#define SHR32(a,shift) ((a) >> (shift))
/** Arithmetic shift-left of a 32-bit value */
#define SHL32(a,shift) ((celt_word32_t)(a) << (shift))
/** 16-bit arithmetic shift right with rounding-to-nearest instead of rounding down */
#define PSHR16(a,shift) (SHR16((a)+((1<<((shift))>>1)),shift))
/** 32-bit arithmetic shift right with rounding-to-nearest instead of rounding down */
#define PSHR32(a,shift) (SHR32((a)+((EXTEND32(1)<<((shift))>>1)),shift))
/** 32-bit arithmetic shift right where the argument can be negative */
#define VSHR32(a, shift) (((shift)>0) ? SHR32(a, shift) : SHL32(a, -(shift)))
/** Saturates 16-bit value to +/- a */
#define SATURATE16(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x)))
/** Saturates 32-bit value to +/- a */
#define SATURATE32(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x)))
/** "RAW" macros, should not be used outside of this header file */
#define SHR(a,shift) ((a) >> (shift))
#define SHL(a,shift) ((celt_word32_t)(a) << (shift))
#define PSHR(a,shift) (SHR((a)+((EXTEND32(1)<<((shift))>>1)),shift))
#define SATURATE(x,a) (((x)>(a) ? (a) : (x)<-(a) ? -(a) : (x)))
/** Shift by a and round-to-neareast 32-bit value. Result is a 16-bit value */
#define ROUND16(x,a) (EXTRACT16(PSHR32((x),(a))))
/** Divide by two */
#define HALF32(x) (SHR32(x,1))
/** Add two 16-bit values */
#define ADD16(a,b) ((celt_word16_t)((celt_word16_t)(a)+(celt_word16_t)(b)))
/** Subtract two 16-bit values */
#define SUB16(a,b) ((celt_word16_t)(a)-(celt_word16_t)(b))
/** Add two 32-bit values */
#define ADD32(a,b) ((celt_word32_t)(a)+(celt_word32_t)(b))
/** Subtract two 32-bit values */
#define SUB32(a,b) ((celt_word32_t)(a)-(celt_word32_t)(b))
/** 16x16 multiplication where the result fits in 16 bits */
#define MULT16_16_16(a,b) ((((celt_word16_t)(a))*((celt_word16_t)(b))))
/* (celt_word32_t)(celt_word16_t) gives TI compiler a hint that it's 16x16->32 multiply */
/** 16x16 multiplication where the result fits in 32 bits */
#define MULT16_16(a,b) (((celt_word32_t)(celt_word16_t)(a))*((celt_word32_t)(celt_word16_t)(b)))
/** 16x16 multiply-add where the result fits in 32 bits */
#define MAC16_16(c,a,b) (ADD32((c),MULT16_16((a),(b))))
/** 16x32 multiplication, followed by a 12-bit shift right. Results fits in 32 bits */
#define MULT16_32_Q12(a,b) ADD32(MULT16_16((a),SHR((b),12)), SHR(MULT16_16((a),((b)&0x00000fff)),12))
/** 16x32 multiplication, followed by a 13-bit shift right. Results fits in 32 bits */
#define MULT16_32_Q13(a,b) ADD32(MULT16_16((a),SHR((b),13)), SHR(MULT16_16((a),((b)&0x00001fff)),13))
/** 16x32 multiplication, followed by a 14-bit shift right. Results fits in 32 bits */
#define MULT16_32_Q14(a,b) ADD32(MULT16_16((a),SHR((b),14)), SHR(MULT16_16((a),((b)&0x00003fff)),14))
/** 16x32 multiplication, followed by an 11-bit shift right. Results fits in 32 bits */
#define MULT16_32_Q11(a,b) ADD32(MULT16_16((a),SHR((b),11)), SHR(MULT16_16((a),((b)&0x000007ff)),11))
/** 16x32 multiply-add, followed by an 11-bit shift right. Results fits in 32 bits */
#define MAC16_32_Q11(c,a,b) ADD32(c,ADD32(MULT16_16((a),SHR((b),11)), SHR(MULT16_16((a),((b)&0x000007ff)),11)))
/** 16x32 multiplication, followed by a 15-bit shift right (round-to-nearest). Results fits in 32 bits */
#define MULT16_32_P15(a,b) ADD32(MULT16_16((a),SHR((b),15)), PSHR(MULT16_16((a),((b)&0x00007fff)),15))
/** 16x32 multiply-add, followed by a 15-bit shift right. Results fits in 32 bits */
#define MAC16_32_Q15(c,a,b) ADD32(c,ADD32(MULT16_16((a),SHR((b),15)), SHR(MULT16_16((a),((b)&0x00007fff)),15)))
#define MAC16_16_Q11(c,a,b) (ADD32((c),SHR(MULT16_16((a),(b)),11)))
#define MAC16_16_Q13(c,a,b) (ADD32((c),SHR(MULT16_16((a),(b)),13)))
#define MAC16_16_P13(c,a,b) (ADD32((c),SHR(ADD32(4096,MULT16_16((a),(b))),13)))
#define MULT16_16_Q11_32(a,b) (SHR(MULT16_16((a),(b)),11))
#define MULT16_16_Q13(a,b) (SHR(MULT16_16((a),(b)),13))
#define MULT16_16_Q14(a,b) (SHR(MULT16_16((a),(b)),14))
#define MULT16_16_Q15(a,b) (SHR(MULT16_16((a),(b)),15))
#define MULT16_16_P13(a,b) (SHR(ADD32(4096,MULT16_16((a),(b))),13))
#define MULT16_16_P14(a,b) (SHR(ADD32(8192,MULT16_16((a),(b))),14))
#define MULT16_16_P15(a,b) (SHR(ADD32(16384,MULT16_16((a),(b))),15))
/** Divide a 32-bit value by a 16-bit value. Result fits in 16 bits */
#define DIV32_16(a,b) ((celt_word16_t)(((celt_word32_t)(a))/((celt_word16_t)(b))))
/** Divide a 32-bit value by a 16-bit value and round to nearest. Result fits in 16 bits */
#define PDIV32_16(a,b) ((celt_word16_t)(((celt_word32_t)(a)+((celt_word16_t)(b)>>1))/((celt_word16_t)(b))))
/** Divide a 32-bit value by a 32-bit value. Result fits in 32 bits */
#define DIV32(a,b) (((celt_word32_t)(a))/((celt_word32_t)(b)))
/** Divide a 32-bit value by a 32-bit value and round to nearest. Result fits in 32 bits */
#define PDIV32(a,b) (((celt_word32_t)(a)+((celt_word16_t)(b)>>1))/((celt_word32_t)(b)))
#endif

114
fmod/lib/libcelt/float_cast.h Executable file
View file

@ -0,0 +1,114 @@
/*
** Copyright (C) 2001 Erik de Castro Lopo <erikd AT mega-nerd DOT com>
**
** Permission to use, copy, modify, distribute, and sell this file for any
** purpose is hereby granted without fee, provided that the above copyright
** and this permission notice appear in all copies. No representations are
** made about the suitability of this software for any purpose. It is
** provided "as is" without express or implied warranty.
*/
/* Version 1.1 */
#ifndef FLOAT_CAST_H
#define FLOAT_CAST_H
/*============================================================================
** On Intel Pentium processors (especially PIII and probably P4), converting
** from float to int is very slow. To meet the C specs, the code produced by
** most C compilers targeting Pentium needs to change the FPU rounding mode
** before the float to int conversion is performed.
**
** Changing the FPU rounding mode causes the FPU pipeline to be flushed. It
** is this flushing of the pipeline which is so slow.
**
** Fortunately the ISO C99 specifications define the functions lrint, lrintf,
** llrint and llrintf which fix this problem as a side effect.
**
** On Unix-like systems, the configure process should have detected the
** presence of these functions. If they weren't found we have to replace them
** here with a standard C cast.
*/
/*
** The C99 prototypes for lrint and lrintf are as follows:
**
** long int lrintf (float x) ;
** long int lrint (double x) ;
*/
/* The presence of the required functions are detected during the configure
** process and the values HAVE_LRINT and HAVE_LRINTF are set accordingly in
** the config.h file.
*/
/* No configure script, define manually */
#if defined(__MACH__)
#define HAVE_LRINTF 1
#endif
#if (HAVE_LRINTF)
/*#if 0*/
/* These defines enable functionality introduced with the 1999 ISO C
** standard. They must be defined before the inclusion of math.h to
** engage them. If optimisation is enabled, these functions will be
** inlined. With optimisation switched off, you have to link in the
** maths library using -lm.
*/
#define _ISOC9X_SOURCE 1
#define _ISOC99_SOURCE 1
#define __USE_ISOC9X 1
#define __USE_ISOC99 1
#include <math.h>
#define float2int(x) lrintf(x)
#elif (defined(HAVE_LRINT))
#define _ISOC9X_SOURCE 1
#define _ISOC99_SOURCE 1
#define __USE_ISOC9X 1
#define __USE_ISOC99 1
#include <math.h>
#define float2int(x) lrint(x)
#elif (defined (WIN32) || defined (_WIN32)) && !defined(_XENON)
#include <math.h>
/* Win32 doesn't seem to have these functions.
** Therefore implement inline versions of these functions here.
*/
__inline long int
float2int (float flt)
{ int intgr;
_asm
{ fld flt
fistp intgr
} ;
return intgr ;
}
#else
#ifdef __GNUC__ /* supported by gcc, but not by all other compilers*/
#warning "Don't have the functions lrint() and lrintf ()."
#warning "Replacing these functions with a standard C cast."
#endif /* __GNUC__ */
#include <math.h>
#define float2int(flt) ((int)(floor(.5+flt)))
#endif
#endif /* FLOAT_CAST_H */

140
fmod/lib/libcelt/header.c Executable file
View file

@ -0,0 +1,140 @@
/* (C) 2008 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "celt_header.h"
#include "os_support.h"
#include "modes.h"
/*typedef struct {
char codec_id[8];
char codec_version[20];
celt_int32_t version_id;
celt_int32_t header_size;
celt_int32_t mode;
celt_int32_t sample_rate;
celt_int32_t nb_channels;
celt_int32_t bytes_per_packet;
celt_int32_t extra_headers;
} CELTHeader;*/
static celt_uint32_t
_le_32 (celt_uint32_t i)
{
celt_uint32_t ret=i;
#if !defined(__LITTLE_ENDIAN__) && ( defined(WORDS_BIGENDIAN) || defined(__BIG_ENDIAN__) )
ret = (i>>24);
ret += (i>>8) & 0x0000ff00;
ret += (i<<8) & 0x00ff0000;
ret += (i<<24);
#endif
return ret;
}
int celt_header_init(CELTHeader *header, const CELTMode *m)
{
if (check_mode(m) != CELT_OK)
return CELT_INVALID_MODE;
if (header==NULL)
return CELT_BAD_ARG;
CELT_COPY(header->codec_id, "CELT ", 8);
CELT_COPY(header->codec_version, "experimental ", 20);
celt_mode_info(m, CELT_GET_BITSTREAM_VERSION, &header->version_id);
header->header_size = 56;
header->sample_rate = m->Fs;
header->nb_channels = m->nbChannels;
header->frame_size = m->mdctSize;
header->overlap = m->overlap;
header->bytes_per_packet = -1;
header->extra_headers = 0;
return CELT_OK;
}
int celt_header_to_packet(const CELTHeader *header, unsigned char *packet, celt_uint32_t size)
{
celt_int32_t * h;
if ((size < 56) || (header==NULL) || (packet==NULL))
return CELT_BAD_ARG; /* FAIL */
CELT_MEMSET(packet, 0, sizeof(*header));
/* FIXME: Do it in an alignment-safe manner */
/* Copy ident and version */
CELT_COPY(packet, (unsigned char*)header, 28);
/* Copy the int32 fields */
h = (celt_int32_t*)(packet+28);
*h++ = _le_32 (header->version_id);
*h++ = _le_32 (header->header_size);
*h++ = _le_32 (header->sample_rate);
*h++ = _le_32 (header->nb_channels);
*h++ = _le_32 (header->frame_size);
*h++ = _le_32 (header->overlap);
*h++ = _le_32 (header->bytes_per_packet);
*h = _le_32 (header->extra_headers);
return sizeof(*header);
}
int celt_header_from_packet(const unsigned char *packet, celt_uint32_t size, CELTHeader *header)
{
celt_int32_t * h;
if ((size < 56) || (header==NULL) || (packet==NULL))
return CELT_BAD_ARG; /* FAIL */
CELT_MEMSET((unsigned char*)header, 0, sizeof(*header));
/* FIXME: Do it in an alignment-safe manner */
/* Copy ident and version */
CELT_COPY((unsigned char*)header, packet, 28);
/* Copy the int32 fields */
h = (celt_int32_t*)(packet+28);
header->version_id = _le_32(*h++);
header->header_size = _le_32(*h++);
header->sample_rate = _le_32(*h++);
header->nb_channels = _le_32(*h++);
header->frame_size = _le_32(*h++);
header->overlap = _le_32(*h++);
header->bytes_per_packet = _le_32(*h++);
header->extra_headers = _le_32(*h);
return sizeof(*header);
}

68
fmod/lib/libcelt/kfft_double.h Executable file
View file

@ -0,0 +1,68 @@
/* (C) 2008 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef KFFT_DOUBLE_H
#define KFFT_DOUBLE_H
#ifdef ENABLE_TI_DSPLIB
#include "dsplib.h"
#include "_kiss_fft_guts.h"
#define cpx32_fft_alloc(length) NULL
#define cpx32_fft_free(state)
#define cpx32_fft(state, X, Y, nx)\
(\
cfft32_SCALE(X,nx),\
cbrev32(X,Y,nx)\
)
#define cpx32_ifft(state, X, Y, nx) \
(\
cifft32_NOSCALE(X,nx),\
cbrev32(X,Y,nx)\
)
#else /* ENABLE_TI_DSPLIB */
#include "kiss_fft.h"
#include "_kiss_fft_guts.h"
#define cpx32_fft_alloc(length) kiss_fft_alloc(length, 0, 0);
#define cpx32_fft_free(state) kiss_fft_free(state)
#define cpx32_fft(state, X, Y, nx) kiss_fft(state,(const kiss_fft_cpx *)(X), (kiss_fft_cpx *)(Y))
#define cpx32_ifft(state, X, Y, nx) kiss_ifft(state,(const kiss_fft_cpx *)(X), (kiss_fft_cpx *)(Y))
#endif /* !ENABLE_TI_DSPLIB */
#endif /* KFFT_DOUBLE_H */

44
fmod/lib/libcelt/kfft_single.c Executable file
View file

@ -0,0 +1,44 @@
/* (C) 2008 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef FIXED_POINT
#include "kfft_single.h"
#define SKIP_CONFIG_H
#include "kiss_fft.c"
#include "kiss_fftr.c"
#endif

84
fmod/lib/libcelt/kfft_single.h Executable file
View file

@ -0,0 +1,84 @@
/* (C) 2008 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef KFFT_SINGLE_H
#define KFFT_SINGLE_H
#ifdef ENABLE_TI_DSPLIB
#include "dsplib.h"
#define real16_fft_alloc(length) NULL
#define real16_fft_free(state)
#define BITREV(state, i) (i)
#define real16_fft_inplace(state, X, nx)\
(\
cfft_SCALE(X,nx/2),\
cbrev(X,X,nx/2),\
unpack(X,nx)\
)
#define real16_ifft(state, X, Y, nx) \
(\
unpacki(X, nx),\
cifft_NOSCALE(X,nx/2),\
cbrev(X,Y,nx/2)\
)
#else /* ENABLE_TI_DSPLIB */
#ifdef FIXED_POINT
#ifdef DOUBLE_PRECISION
#undef DOUBLE_PRECISION
#endif
#ifdef MIXED_PRECISION
#undef MIXED_PRECISION
#endif
#endif /* FIXED_POINT */
#include "kiss_fft.h"
#include "kiss_fftr.h"
#include "_kiss_fft_guts.h"
#define real16_fft_alloc(length) kiss_fftr_alloc_celt_single(length, 0, 0);
#define real16_fft_free(state) kiss_fft_free(state)
#define real16_fft_inplace(state, X, nx) kiss_fftr_inplace(state,X)
#define BITREV(state, i) ((state)->substate->bitrev[i])
#define real16_ifft(state, X, Y, nx) kiss_fftri(state,X, Y)
#endif /* !ENABLE_TI_DSPLIB */
#endif /* KFFT_SINGLE_H */

701
fmod/lib/libcelt/kiss_fft.c Executable file
View file

@ -0,0 +1,701 @@
/*
Copyright (c) 2003-2004, Mark Borgerding
Lots of modifications by JMV
Copyright (c) 2005-2007, Jean-Marc Valin
Copyright (c) 2008, Jean-Marc Valin, CSIRO
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SKIP_CONFIG_H
# ifdef HAVE_CONFIG_H
# include "config.h"
# endif
#endif
#include "_kiss_fft_guts.h"
#include "arch.h"
#include "os_support.h"
#include "mathops.h"
#include "stack_alloc.h"
/* The guts header contains all the multiplication and addition macros that are defined for
complex numbers. It also delares the kf_ internal functions.
*/
static void kf_bfly2(
kiss_fft_cpx * Fout,
const size_t fstride,
const kiss_fft_cfg st,
int m,
int N,
int mm
)
{
kiss_fft_cpx * Fout2;
kiss_twiddle_cpx * tw1;
int i,j;
kiss_fft_cpx * Fout_beg = Fout;
for (i=0;i<N;i++)
{
Fout = Fout_beg + i*mm;
Fout2 = Fout + m;
tw1 = st->twiddles;
for(j=0;j<m;j++)
{
kiss_fft_cpx t;
Fout->r = SHR(Fout->r, 1);Fout->i = SHR(Fout->i, 1);
Fout2->r = SHR(Fout2->r, 1);Fout2->i = SHR(Fout2->i, 1);
C_MUL (t, *Fout2 , *tw1);
tw1 += fstride;
C_SUB( *Fout2 , *Fout , t );
C_ADDTO( *Fout , t );
++Fout2;
++Fout;
}
}
}
static void ki_bfly2(
kiss_fft_cpx * Fout,
const size_t fstride,
const kiss_fft_cfg st,
int m,
int N,
int mm
)
{
kiss_fft_cpx * Fout2;
kiss_twiddle_cpx * tw1;
kiss_fft_cpx t;
int i,j;
kiss_fft_cpx * Fout_beg = Fout;
for (i=0;i<N;i++)
{
Fout = Fout_beg + i*mm;
Fout2 = Fout + m;
tw1 = st->twiddles;
for(j=0;j<m;j++)
{
C_MULC (t, *Fout2 , *tw1);
tw1 += fstride;
C_SUB( *Fout2 , *Fout , t );
C_ADDTO( *Fout , t );
++Fout2;
++Fout;
}
}
}
static void kf_bfly4(
kiss_fft_cpx * Fout,
const size_t fstride,
const kiss_fft_cfg st,
int m,
int N,
int mm
)
{
kiss_twiddle_cpx *tw1,*tw2,*tw3;
kiss_fft_cpx scratch[6];
const size_t m2=2*m;
const size_t m3=3*m;
int i, j;
kiss_fft_cpx * Fout_beg = Fout;
for (i=0;i<N;i++)
{
Fout = Fout_beg + i*mm;
tw3 = tw2 = tw1 = st->twiddles;
for (j=0;j<m;j++)
{
C_MUL4(scratch[0],Fout[m] , *tw1 );
C_MUL4(scratch[1],Fout[m2] , *tw2 );
C_MUL4(scratch[2],Fout[m3] , *tw3 );
Fout->r = PSHR(Fout->r, 2);
Fout->i = PSHR(Fout->i, 2);
C_SUB( scratch[5] , *Fout, scratch[1] );
C_ADDTO(*Fout, scratch[1]);
C_ADD( scratch[3] , scratch[0] , scratch[2] );
C_SUB( scratch[4] , scratch[0] , scratch[2] );
Fout[m2].r = PSHR(Fout[m2].r, 2);
Fout[m2].i = PSHR(Fout[m2].i, 2);
C_SUB( Fout[m2], *Fout, scratch[3] );
tw1 += fstride;
tw2 += fstride*2;
tw3 += fstride*3;
C_ADDTO( *Fout , scratch[3] );
Fout[m].r = scratch[5].r + scratch[4].i;
Fout[m].i = scratch[5].i - scratch[4].r;
Fout[m3].r = scratch[5].r - scratch[4].i;
Fout[m3].i = scratch[5].i + scratch[4].r;
++Fout;
}
}
}
static void ki_bfly4(
kiss_fft_cpx * Fout,
const size_t fstride,
const kiss_fft_cfg st,
int m,
int N,
int mm
)
{
kiss_twiddle_cpx *tw1,*tw2,*tw3;
kiss_fft_cpx scratch[6];
const size_t m2=2*m;
const size_t m3=3*m;
int i, j;
kiss_fft_cpx * Fout_beg = Fout;
for (i=0;i<N;i++)
{
Fout = Fout_beg + i*mm;
tw3 = tw2 = tw1 = st->twiddles;
for (j=0;j<m;j++)
{
C_MULC(scratch[0],Fout[m] , *tw1 );
C_MULC(scratch[1],Fout[m2] , *tw2 );
C_MULC(scratch[2],Fout[m3] , *tw3 );
C_SUB( scratch[5] , *Fout, scratch[1] );
C_ADDTO(*Fout, scratch[1]);
C_ADD( scratch[3] , scratch[0] , scratch[2] );
C_SUB( scratch[4] , scratch[0] , scratch[2] );
C_SUB( Fout[m2], *Fout, scratch[3] );
tw1 += fstride;
tw2 += fstride*2;
tw3 += fstride*3;
C_ADDTO( *Fout , scratch[3] );
Fout[m].r = scratch[5].r - scratch[4].i;
Fout[m].i = scratch[5].i + scratch[4].r;
Fout[m3].r = scratch[5].r + scratch[4].i;
Fout[m3].i = scratch[5].i - scratch[4].r;
++Fout;
}
}
}
#ifndef RADIX_TWO_ONLY
static void kf_bfly3(
kiss_fft_cpx * Fout,
const size_t fstride,
const kiss_fft_cfg st,
size_t m
)
{
size_t k=m;
const size_t m2 = 2*m;
kiss_twiddle_cpx *tw1,*tw2;
kiss_fft_cpx scratch[5];
kiss_twiddle_cpx epi3;
epi3 = st->twiddles[fstride*m];
tw1=tw2=st->twiddles;
do{
C_FIXDIV(*Fout,3); C_FIXDIV(Fout[m],3); C_FIXDIV(Fout[m2],3);
C_MUL(scratch[1],Fout[m] , *tw1);
C_MUL(scratch[2],Fout[m2] , *tw2);
C_ADD(scratch[3],scratch[1],scratch[2]);
C_SUB(scratch[0],scratch[1],scratch[2]);
tw1 += fstride;
tw2 += fstride*2;
Fout[m].r = Fout->r - HALF_OF(scratch[3].r);
Fout[m].i = Fout->i - HALF_OF(scratch[3].i);
C_MULBYSCALAR( scratch[0] , epi3.i );
C_ADDTO(*Fout,scratch[3]);
Fout[m2].r = Fout[m].r + scratch[0].i;
Fout[m2].i = Fout[m].i - scratch[0].r;
Fout[m].r -= scratch[0].i;
Fout[m].i += scratch[0].r;
++Fout;
}while(--k);
}
static void ki_bfly3(
kiss_fft_cpx * Fout,
const size_t fstride,
const kiss_fft_cfg st,
size_t m
)
{
size_t k=m;
const size_t m2 = 2*m;
kiss_twiddle_cpx *tw1,*tw2;
kiss_fft_cpx scratch[5];
kiss_twiddle_cpx epi3;
epi3 = st->twiddles[fstride*m];
tw1=tw2=st->twiddles;
do{
C_MULC(scratch[1],Fout[m] , *tw1);
C_MULC(scratch[2],Fout[m2] , *tw2);
C_ADD(scratch[3],scratch[1],scratch[2]);
C_SUB(scratch[0],scratch[1],scratch[2]);
tw1 += fstride;
tw2 += fstride*2;
Fout[m].r = Fout->r - HALF_OF(scratch[3].r);
Fout[m].i = Fout->i - HALF_OF(scratch[3].i);
C_MULBYSCALAR( scratch[0] , -epi3.i );
C_ADDTO(*Fout,scratch[3]);
Fout[m2].r = Fout[m].r + scratch[0].i;
Fout[m2].i = Fout[m].i - scratch[0].r;
Fout[m].r -= scratch[0].i;
Fout[m].i += scratch[0].r;
++Fout;
}while(--k);
}
static void kf_bfly5(
kiss_fft_cpx * Fout,
const size_t fstride,
const kiss_fft_cfg st,
int m
)
{
kiss_fft_cpx *Fout0,*Fout1,*Fout2,*Fout3,*Fout4;
int u;
kiss_fft_cpx scratch[13];
kiss_twiddle_cpx * twiddles = st->twiddles;
kiss_twiddle_cpx *tw;
kiss_twiddle_cpx ya,yb;
ya = twiddles[fstride*m];
yb = twiddles[fstride*2*m];
Fout0=Fout;
Fout1=Fout0+m;
Fout2=Fout0+2*m;
Fout3=Fout0+3*m;
Fout4=Fout0+4*m;
tw=st->twiddles;
for ( u=0; u<m; ++u ) {
C_FIXDIV( *Fout0,5); C_FIXDIV( *Fout1,5); C_FIXDIV( *Fout2,5); C_FIXDIV( *Fout3,5); C_FIXDIV( *Fout4,5);
scratch[0] = *Fout0;
C_MUL(scratch[1] ,*Fout1, tw[u*fstride]);
C_MUL(scratch[2] ,*Fout2, tw[2*u*fstride]);
C_MUL(scratch[3] ,*Fout3, tw[3*u*fstride]);
C_MUL(scratch[4] ,*Fout4, tw[4*u*fstride]);
C_ADD( scratch[7],scratch[1],scratch[4]);
C_SUB( scratch[10],scratch[1],scratch[4]);
C_ADD( scratch[8],scratch[2],scratch[3]);
C_SUB( scratch[9],scratch[2],scratch[3]);
Fout0->r += scratch[7].r + scratch[8].r;
Fout0->i += scratch[7].i + scratch[8].i;
scratch[5].r = scratch[0].r + S_MUL(scratch[7].r,ya.r) + S_MUL(scratch[8].r,yb.r);
scratch[5].i = scratch[0].i + S_MUL(scratch[7].i,ya.r) + S_MUL(scratch[8].i,yb.r);
scratch[6].r = S_MUL(scratch[10].i,ya.i) + S_MUL(scratch[9].i,yb.i);
scratch[6].i = -S_MUL(scratch[10].r,ya.i) - S_MUL(scratch[9].r,yb.i);
C_SUB(*Fout1,scratch[5],scratch[6]);
C_ADD(*Fout4,scratch[5],scratch[6]);
scratch[11].r = scratch[0].r + S_MUL(scratch[7].r,yb.r) + S_MUL(scratch[8].r,ya.r);
scratch[11].i = scratch[0].i + S_MUL(scratch[7].i,yb.r) + S_MUL(scratch[8].i,ya.r);
scratch[12].r = - S_MUL(scratch[10].i,yb.i) + S_MUL(scratch[9].i,ya.i);
scratch[12].i = S_MUL(scratch[10].r,yb.i) - S_MUL(scratch[9].r,ya.i);
C_ADD(*Fout2,scratch[11],scratch[12]);
C_SUB(*Fout3,scratch[11],scratch[12]);
++Fout0;++Fout1;++Fout2;++Fout3;++Fout4;
}
}
static void ki_bfly5(
kiss_fft_cpx * Fout,
const size_t fstride,
const kiss_fft_cfg st,
int m
)
{
kiss_fft_cpx *Fout0,*Fout1,*Fout2,*Fout3,*Fout4;
int u;
kiss_fft_cpx scratch[13];
kiss_twiddle_cpx * twiddles = st->twiddles;
kiss_twiddle_cpx *tw;
kiss_twiddle_cpx ya,yb;
ya = twiddles[fstride*m];
yb = twiddles[fstride*2*m];
Fout0=Fout;
Fout1=Fout0+m;
Fout2=Fout0+2*m;
Fout3=Fout0+3*m;
Fout4=Fout0+4*m;
tw=st->twiddles;
for ( u=0; u<m; ++u ) {
scratch[0] = *Fout0;
C_MULC(scratch[1] ,*Fout1, tw[u*fstride]);
C_MULC(scratch[2] ,*Fout2, tw[2*u*fstride]);
C_MULC(scratch[3] ,*Fout3, tw[3*u*fstride]);
C_MULC(scratch[4] ,*Fout4, tw[4*u*fstride]);
C_ADD( scratch[7],scratch[1],scratch[4]);
C_SUB( scratch[10],scratch[1],scratch[4]);
C_ADD( scratch[8],scratch[2],scratch[3]);
C_SUB( scratch[9],scratch[2],scratch[3]);
Fout0->r += scratch[7].r + scratch[8].r;
Fout0->i += scratch[7].i + scratch[8].i;
scratch[5].r = scratch[0].r + S_MUL(scratch[7].r,ya.r) + S_MUL(scratch[8].r,yb.r);
scratch[5].i = scratch[0].i + S_MUL(scratch[7].i,ya.r) + S_MUL(scratch[8].i,yb.r);
scratch[6].r = -S_MUL(scratch[10].i,ya.i) - S_MUL(scratch[9].i,yb.i);
scratch[6].i = S_MUL(scratch[10].r,ya.i) + S_MUL(scratch[9].r,yb.i);
C_SUB(*Fout1,scratch[5],scratch[6]);
C_ADD(*Fout4,scratch[5],scratch[6]);
scratch[11].r = scratch[0].r + S_MUL(scratch[7].r,yb.r) + S_MUL(scratch[8].r,ya.r);
scratch[11].i = scratch[0].i + S_MUL(scratch[7].i,yb.r) + S_MUL(scratch[8].i,ya.r);
scratch[12].r = S_MUL(scratch[10].i,yb.i) - S_MUL(scratch[9].i,ya.i);
scratch[12].i = -S_MUL(scratch[10].r,yb.i) + S_MUL(scratch[9].r,ya.i);
C_ADD(*Fout2,scratch[11],scratch[12]);
C_SUB(*Fout3,scratch[11],scratch[12]);
++Fout0;++Fout1;++Fout2;++Fout3;++Fout4;
}
}
/* perform the butterfly for one stage of a mixed radix FFT */
static void kf_bfly_generic(
kiss_fft_cpx * Fout,
const size_t fstride,
const kiss_fft_cfg st,
int m,
int p
)
{
int u,k,q1,q;
kiss_twiddle_cpx * twiddles = st->twiddles;
kiss_fft_cpx t;
VARDECL(kiss_fft_cpx, scratchbuf);
int Norig = st->nfft;
ALLOC(scratchbuf, p, kiss_fft_cpx);
for ( u=0; u<m; ++u ) {
k=u;
for ( q1=0 ; q1<p ; ++q1 ) {
scratchbuf[q1] = Fout[ k ];
C_FIXDIV(scratchbuf[q1],p);
k += m;
}
k=u;
for ( q1=0 ; q1<p ; ++q1 ) {
int twidx=0;
Fout[ k ] = scratchbuf[0];
for (q=1;q<p;++q ) {
twidx += fstride * k;
if (twidx>=Norig) twidx-=Norig;
C_MUL(t,scratchbuf[q] , twiddles[twidx] );
C_ADDTO( Fout[ k ] ,t);
}
k += m;
}
}
}
static void ki_bfly_generic(
kiss_fft_cpx * Fout,
const size_t fstride,
const kiss_fft_cfg st,
int m,
int p
)
{
int u,k,q1,q;
kiss_twiddle_cpx * twiddles = st->twiddles;
kiss_fft_cpx t;
VARDECL(kiss_fft_cpx, scratchbuf);
int Norig = st->nfft;
ALLOC(scratchbuf, p, kiss_fft_cpx);
for ( u=0; u<m; ++u ) {
k=u;
for ( q1=0 ; q1<p ; ++q1 ) {
scratchbuf[q1] = Fout[ k ];
k += m;
}
k=u;
for ( q1=0 ; q1<p ; ++q1 ) {
int twidx=0;
Fout[ k ] = scratchbuf[0];
for (q=1;q<p;++q ) {
twidx += fstride * k;
if (twidx>=Norig) twidx-=Norig;
C_MULC(t,scratchbuf[q] , twiddles[twidx] );
C_ADDTO( Fout[ k ] ,t);
}
k += m;
}
}
}
#endif
static
void compute_bitrev_table(
int Fout,
int *f,
const size_t fstride,
int in_stride,
int * factors,
const kiss_fft_cfg st
)
{
const int p=*factors++; /* the radix */
const int m=*factors++; /* stage's fft length/p */
/*printf ("fft %d %d %d %d %d %d\n", p*m, m, p, s2, fstride*in_stride, N);*/
if (m==1)
{
int j;
for (j=0;j<p;j++)
{
*f = Fout+j;
f += fstride*in_stride;
}
} else {
int j;
for (j=0;j<p;j++)
{
compute_bitrev_table( Fout , f, fstride*p, in_stride, factors,st);
f += fstride*in_stride;
Fout += m;
}
}
}
void kf_work(
kiss_fft_cpx * Fout,
const kiss_fft_cpx * f,
const size_t fstride,
int in_stride,
int * factors,
const kiss_fft_cfg st,
int N,
int s2,
int m2
)
{
#ifndef RADIX_TWO_ONLY
int i;
kiss_fft_cpx * Fout_beg=Fout;
#endif
const int p=*factors++; /* the radix */
const int m=*factors++; /* stage's fft length/p */
/*printf ("fft %d %d %d %d %d %d %d\n", p*m, m, p, s2, fstride*in_stride, N, m2);*/
if (m!=1)
kf_work( Fout , f, fstride*p, in_stride, factors,st, N*p, fstride*in_stride, m);
switch (p) {
case 2: kf_bfly2(Fout,fstride,st,m, N, m2); break;
case 4: kf_bfly4(Fout,fstride,st,m, N, m2); break;
#ifndef RADIX_TWO_ONLY
case 3: for (i=0;i<N;i++){Fout=Fout_beg+i*m2; kf_bfly3(Fout,fstride,st,m);} break;
case 5: for (i=0;i<N;i++){Fout=Fout_beg+i*m2; kf_bfly5(Fout,fstride,st,m);} break;
default: for (i=0;i<N;i++){Fout=Fout_beg+i*m2; kf_bfly_generic(Fout,fstride,st,m,p);} break;
#else
default: celt_fatal("kiss_fft: only powers of two enabled");
#endif
}
}
void ki_work(
kiss_fft_cpx * Fout,
const kiss_fft_cpx * f,
const size_t fstride,
int in_stride,
int * factors,
const kiss_fft_cfg st,
int N,
int s2,
int m2
)
{
#ifndef RADIX_TWO_ONLY
int i;
kiss_fft_cpx * Fout_beg=Fout;
#endif
const int p=*factors++; /* the radix */
const int m=*factors++; /* stage's fft length/p */
/*printf ("fft %d %d %d %d %d %d %d\n", p*m, m, p, s2, fstride*in_stride, N, m2);*/
if (m!=1)
ki_work( Fout , f, fstride*p, in_stride, factors,st, N*p, fstride*in_stride, m);
switch (p) {
case 2: ki_bfly2(Fout,fstride,st,m, N, m2); break;
case 4: ki_bfly4(Fout,fstride,st,m, N, m2); break;
#ifndef RADIX_TWO_ONLY
case 3: for (i=0;i<N;i++){Fout=Fout_beg+i*m2; ki_bfly3(Fout,fstride,st,m);} break;
case 5: for (i=0;i<N;i++){Fout=Fout_beg+i*m2; ki_bfly5(Fout,fstride,st,m);} break;
default: for (i=0;i<N;i++){Fout=Fout_beg+i*m2; ki_bfly_generic(Fout,fstride,st,m,p);} break;
#else
default: celt_fatal("kiss_fft: only powers of two enabled");
#endif
}
}
/* facbuf is populated by p1,m1,p2,m2, ...
where
p[i] * m[i] = m[i-1]
m0 = n */
static
void kf_factor(int n,int * facbuf)
{
int p=4;
/*factor out powers of 4, powers of 2, then any remaining primes */
do {
while (n % p) {
switch (p) {
case 4: p = 2; break;
case 2: p = 3; break;
default: p += 2; break;
}
if (p>32000 || (celt_int32_t)p*(celt_int32_t)p > n)
p = n; /* no more factors, skip to end */
}
n /= p;
*facbuf++ = p;
*facbuf++ = n;
} while (n > 1);
}
/*
*
* User-callable function to allocate all necessary storage space for the fft.
*
* The return value is a contiguous block of memory, allocated with malloc. As such,
* It can be freed with free(), rather than a kiss_fft-specific function.
* */
kiss_fft_cfg kiss_fft_alloc(int nfft,void * mem,size_t * lenmem )
{
kiss_fft_cfg st=NULL;
size_t memneeded = sizeof(struct kiss_fft_state)
+ sizeof(kiss_twiddle_cpx)*(nfft-1) + sizeof(int)*nfft; /* twiddle factors*/
if ( lenmem==NULL ) {
st = ( kiss_fft_cfg)KISS_FFT_MALLOC( memneeded );
}else{
if (mem != NULL && *lenmem >= memneeded)
st = (kiss_fft_cfg)mem;
*lenmem = memneeded;
}
if (st) {
int i;
st->nfft=nfft;
#ifndef FIXED_POINT
st->scale = 1./nfft;
#endif
#if defined(FIXED_POINT) && (!defined(DOUBLE_PRECISION) || defined(MIXED_PRECISION))
for (i=0;i<nfft;++i) {
celt_word32_t phase = -i;
kf_cexp2(st->twiddles+i, DIV32(SHL32(phase,17),nfft));
}
#else
for (i=0;i<nfft;++i) {
const double pi=3.14159265358979323846264338327;
double phase = ( -2*pi /nfft ) * i;
kf_cexp(st->twiddles+i, phase );
}
#endif
kf_factor(nfft,st->factors);
/* bitrev */
st->bitrev = (int*)((char*)st + memneeded - sizeof(int)*nfft);
compute_bitrev_table(0, st->bitrev, 1,1, st->factors,st);
}
return st;
}
void kiss_fft_stride(kiss_fft_cfg st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int in_stride)
{
if (fin == fout)
{
celt_fatal("In-place FFT not supported");
} else {
/* Bit-reverse the input */
int i;
for (i=0;i<st->nfft;i++)
{
fout[st->bitrev[i]] = fin[i];
#ifndef FIXED_POINT
fout[st->bitrev[i]].r *= st->scale;
fout[st->bitrev[i]].i *= st->scale;
#endif
}
kf_work( fout, fin, 1,in_stride, st->factors,st, 1, in_stride, 1);
}
}
void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout)
{
kiss_fft_stride(cfg,fin,fout,1);
}
void kiss_ifft_stride(kiss_fft_cfg st,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int in_stride)
{
if (fin == fout)
{
celt_fatal("In-place FFT not supported");
} else {
/* Bit-reverse the input */
int i;
for (i=0;i<st->nfft;i++)
fout[st->bitrev[i]] = fin[i];
ki_work( fout, fin, 1,in_stride, st->factors,st, 1, in_stride, 1);
}
}
void kiss_ifft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout)
{
kiss_ifft_stride(cfg,fin,fout,1);
}

159
fmod/lib/libcelt/kiss_fft.h Executable file
View file

@ -0,0 +1,159 @@
/*
Copyright (c) 2003-2004, Mark Borgerding
Lots of modifications by JMV
Copyright (c) 2005-2007, Jean-Marc Valin
Copyright (c) 2008, Jean-Marc Valin, CSIRO
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef KISS_FFT_H
#define KISS_FFT_H
#include <stdlib.h>
#include <math.h>
#include "arch.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
ATTENTION!
If you would like a :
-- a utility that will handle the caching of fft objects
-- real-only (no imaginary time component ) FFT
-- a multi-dimensional FFT
-- a command-line utility to perform ffts
-- a command-line utility to perform fast-convolution filtering
Then see kfc.h kiss_fftr.h kiss_fftnd.h fftutil.c kiss_fastfir.c
in the tools/ directory.
*/
#ifdef USE_SIMD
# include <xmmintrin.h>
# define kiss_fft_scalar __m128
#define KISS_FFT_MALLOC(nbytes) memalign(16,nbytes)
#else
#define KISS_FFT_MALLOC celt_alloc
#endif
#ifdef FIXED_POINT
#include "arch.h"
#ifdef DOUBLE_PRECISION
# define kiss_fft_scalar celt_int32_t
# define kiss_twiddle_scalar celt_int32_t
# define KF_SUFFIX _celt_double
#else
# define kiss_fft_scalar celt_int16_t
# define kiss_twiddle_scalar celt_int16_t
# define KF_SUFFIX _celt_single
#endif
#else
# ifndef kiss_fft_scalar
/* default is float */
# define kiss_fft_scalar float
# define kiss_twiddle_scalar float
# define KF_SUFFIX _celt_single
# endif
#endif
/* This adds a suffix to all the kiss_fft functions so we
can easily link with more than one copy of the fft */
#define CAT_SUFFIX(a,b) a ## b
#define SUF(a,b) CAT_SUFFIX(a, b)
#define kiss_fft_alloc SUF(kiss_fft_alloc,KF_SUFFIX)
#define kf_work SUF(kf_work,KF_SUFFIX)
#define ki_work SUF(ki_work,KF_SUFFIX)
#define kiss_fft SUF(kiss_fft,KF_SUFFIX)
#define kiss_ifft SUF(kiss_ifft,KF_SUFFIX)
#define kiss_fft_stride SUF(kiss_fft_stride,KF_SUFFIX)
#define kiss_ifft_stride SUF(kiss_ifft_stride,KF_SUFFIX)
typedef struct {
kiss_fft_scalar r;
kiss_fft_scalar i;
}kiss_fft_cpx;
typedef struct {
kiss_twiddle_scalar r;
kiss_twiddle_scalar i;
}kiss_twiddle_cpx;
typedef struct kiss_fft_state* kiss_fft_cfg;
/**
* kiss_fft_alloc
*
* Initialize a FFT (or IFFT) algorithm's cfg/state buffer.
*
* typical usage: kiss_fft_cfg mycfg=kiss_fft_alloc(1024,0,NULL,NULL);
*
* The return value from fft_alloc is a cfg buffer used internally
* by the fft routine or NULL.
*
* If lenmem is NULL, then kiss_fft_alloc will allocate a cfg buffer using malloc.
* The returned value should be free()d when done to avoid memory leaks.
*
* The state can be placed in a user supplied buffer 'mem':
* If lenmem is not NULL and mem is not NULL and *lenmem is large enough,
* then the function places the cfg in mem and the size used in *lenmem
* and returns mem.
*
* If lenmem is not NULL and ( mem is NULL or *lenmem is not large enough),
* then the function returns NULL and places the minimum cfg
* buffer size in *lenmem.
* */
kiss_fft_cfg kiss_fft_alloc(int nfft,void * mem,size_t * lenmem);
void kf_work(kiss_fft_cpx * Fout,const kiss_fft_cpx * f,const size_t fstride,
int in_stride,int * factors,const kiss_fft_cfg st,int N,int s2,int m2);
/** Internal function. Can be useful when you want to do the bit-reversing yourself */
void ki_work(kiss_fft_cpx * Fout, const kiss_fft_cpx * f, const size_t fstride,
int in_stride,int * factors,const kiss_fft_cfg st,int N,int s2,int m2);
/**
* kiss_fft(cfg,in_out_buf)
*
* Perform an FFT on a complex input buffer.
* for a forward FFT,
* fin should be f[0] , f[1] , ... ,f[nfft-1]
* fout will be F[0] , F[1] , ... ,F[nfft-1]
* Note that each element is complex and can be accessed like
f[k].r and f[k].i
* */
void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout);
void kiss_ifft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout);
/**
A more generic version of the above function. It reads its input from every Nth sample.
* */
void kiss_fft_stride(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int fin_stride);
void kiss_ifft_stride(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int fin_stride);
/** If kiss_fft_alloc allocated a buffer, it is one contiguous
buffer and can be simply free()d when no longer needed*/
#define kiss_fft_free celt_free
#ifdef __cplusplus
}
#endif
#endif

165
fmod/lib/libcelt/kiss_fftr.c Executable file
View file

@ -0,0 +1,165 @@
/*
Original version:
Copyright (c) 2003-2004, Mark Borgerding
Followed by heavy modifications:
Copyright (c) 2007-2008, Jean-Marc Valin
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SKIP_CONFIG_H
# ifdef HAVE_CONFIG_H
# include "config.h"
# endif
#endif
#include "os_support.h"
#include "mathops.h"
#include "kiss_fftr.h"
#include "_kiss_fft_guts.h"
kiss_fftr_cfg kiss_fftr_alloc(int nfft,void * mem,size_t * lenmem)
{
int i;
int twiddle_size;
kiss_fftr_cfg st = NULL;
size_t subsize, memneeded;
if (nfft & 1) {
celt_warning("Real FFT optimization must be even.\n");
return NULL;
}
nfft >>= 1;
twiddle_size = nfft/2+1;
kiss_fft_alloc (nfft, NULL, &subsize);
memneeded = sizeof(struct kiss_fftr_state) + subsize + sizeof(kiss_twiddle_cpx)*twiddle_size;
if (lenmem == NULL) {
st = (kiss_fftr_cfg) KISS_FFT_MALLOC (memneeded);
} else {
if (*lenmem >= memneeded)
st = (kiss_fftr_cfg) mem;
*lenmem = memneeded;
}
if (!st)
return NULL;
st->substate = (kiss_fft_cfg) (st + 1); /*just beyond kiss_fftr_state struct */
st->super_twiddles = (kiss_twiddle_cpx*) (((char *) st->substate) + subsize);
kiss_fft_alloc(nfft, st->substate, &subsize);
#ifndef FIXED_POINT
st->substate->scale *= .5;
#endif
#if defined (FIXED_POINT) && (!defined(DOUBLE_PRECISION) || defined(MIXED_PRECISION))
for (i=0;i<twiddle_size;++i) {
celt_word32_t phase = i+(nfft>>1);
kf_cexp2(st->super_twiddles+i, DIV32(SHL32(phase,16),nfft));
}
#else
for (i=0;i<twiddle_size;++i) {
const double pi=3.14159265358979323846264338327;
double phase = pi*(((double)i) /nfft + .5);
kf_cexp(st->super_twiddles+i, phase );
}
#endif
return st;
}
void kiss_fftr_twiddles(kiss_fftr_cfg st,kiss_fft_scalar *freqdata)
{
/* input buffer timedata is stored row-wise */
int k,ncfft;
kiss_fft_cpx f2k,f1k,tdc,tw;
ncfft = st->substate->nfft;
/* The real part of the DC element of the frequency spectrum in st->tmpbuf
* contains the sum of the even-numbered elements of the input time sequence
* The imag part is the sum of the odd-numbered elements
*
* The sum of tdc.r and tdc.i is the sum of the input time sequence.
* yielding DC of input time sequence
* The difference of tdc.r - tdc.i is the sum of the input (dot product) [1,-1,1,-1...
* yielding Nyquist bin of input time sequence
*/
tdc.r = freqdata[0];
tdc.i = freqdata[1];
C_FIXDIV(tdc,2);
CHECK_OVERFLOW_OP(tdc.r ,+, tdc.i);
CHECK_OVERFLOW_OP(tdc.r ,-, tdc.i);
freqdata[0] = tdc.r + tdc.i;
freqdata[1] = tdc.r - tdc.i;
for ( k=1;k <= ncfft/2 ; ++k )
{
f2k.r = SHR32(SUB32(EXT32(freqdata[2*k]), EXT32(freqdata[2*(ncfft-k)])),1);
f2k.i = PSHR32(ADD32(EXT32(freqdata[2*k+1]), EXT32(freqdata[2*(ncfft-k)+1])),1);
f1k.r = SHR32(ADD32(EXT32(freqdata[2*k]), EXT32(freqdata[2*(ncfft-k)])),1);
f1k.i = SHR32(SUB32(EXT32(freqdata[2*k+1]), EXT32(freqdata[2*(ncfft-k)+1])),1);
C_MULC( tw , f2k , st->super_twiddles[k]);
freqdata[2*k] = HALF_OF(f1k.r + tw.r);
freqdata[2*k+1] = HALF_OF(f1k.i + tw.i);
freqdata[2*(ncfft-k)] = HALF_OF(f1k.r - tw.r);
freqdata[2*(ncfft-k)+1] = HALF_OF(tw.i - f1k.i);
}
}
void kiss_fftr(kiss_fftr_cfg st,const kiss_fft_scalar *timedata,kiss_fft_scalar *freqdata)
{
/*perform the parallel fft of two real signals packed in real,imag*/
kiss_fft( st->substate , (const kiss_fft_cpx*)timedata, (kiss_fft_cpx *)freqdata );
kiss_fftr_twiddles(st,freqdata);
}
void kiss_fftr_inplace(kiss_fftr_cfg st, kiss_fft_scalar *X)
{
kf_work((kiss_fft_cpx*)X, NULL, 1,1, st->substate->factors,st->substate, 1, 1, 1);
kiss_fftr_twiddles(st,X);
}
void kiss_fftri(kiss_fftr_cfg st,const kiss_fft_scalar *freqdata,kiss_fft_scalar *timedata)
{
/* input buffer timedata is stored row-wise */
int k, ncfft;
ncfft = st->substate->nfft;
timedata[2*st->substate->bitrev[0]] = freqdata[0] + freqdata[1];
timedata[2*st->substate->bitrev[0]+1] = freqdata[0] - freqdata[1];
for (k = 1; k <= ncfft / 2; ++k) {
kiss_fft_cpx fk, fnkc, fek, fok, tmp;
int k1, k2;
k1 = st->substate->bitrev[k];
k2 = st->substate->bitrev[ncfft-k];
fk.r = freqdata[2*k];
fk.i = freqdata[2*k+1];
fnkc.r = freqdata[2*(ncfft-k)];
fnkc.i = -freqdata[2*(ncfft-k)+1];
C_ADD (fek, fk, fnkc);
C_SUB (tmp, fk, fnkc);
C_MUL (fok, tmp, st->super_twiddles[k]);
timedata[2*k1] = fek.r + fok.r;
timedata[2*k1+1] = fek.i + fok.i;
timedata[2*k2] = fek.r - fok.r;
timedata[2*k2+1] = fok.i - fek.i;
}
ki_work((kiss_fft_cpx*)timedata, NULL, 1,1, st->substate->factors,st->substate, 1, 1, 1);
}

82
fmod/lib/libcelt/kiss_fftr.h Executable file
View file

@ -0,0 +1,82 @@
/*
Original version:
Copyright (c) 2003-2004, Mark Borgerding
Followed by heavy modifications:
Copyright (c) 2007-2008, Jean-Marc Valin
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef KISS_FTR_H
#define KISS_FTR_H
#include "kiss_fft.h"
#ifdef __cplusplus
extern "C" {
#endif
#define kiss_fftr_alloc SUF(kiss_fftr_alloc,KF_SUFFIX)
#define kiss_fftr_inplace SUF(kiss_fftr_inplace,KF_SUFFIX)
#define kiss_fftr_alloc SUF(kiss_fftr_alloc,KF_SUFFIX)
#define kiss_fftr_twiddles SUF(kiss_fftr_twiddles,KF_SUFFIX)
#define kiss_fftr SUF(kiss_fftr,KF_SUFFIX)
#define kiss_fftri SUF(kiss_fftri,KF_SUFFIX)
/*
Real optimized version can save about 45% cpu time vs. complex fft of a real seq.
*/
struct kiss_fftr_state{
kiss_fft_cfg substate;
kiss_twiddle_cpx * super_twiddles;
#ifdef USE_SIMD
long pad;
#endif
};
typedef struct kiss_fftr_state *kiss_fftr_cfg;
kiss_fftr_cfg kiss_fftr_alloc(int nfft,void * mem, size_t * lenmem);
/*
nfft must be even
If you don't care to allocate space, use mem = lenmem = NULL
*/
/*
input timedata has nfft scalar points
output freqdata has nfft/2+1 complex points, packed into nfft scalar points
*/
void kiss_fftr_twiddles(kiss_fftr_cfg st,kiss_fft_scalar *freqdata);
void kiss_fftr(kiss_fftr_cfg st,const kiss_fft_scalar *timedata,kiss_fft_scalar *freqdata);
void kiss_fftr_inplace(kiss_fftr_cfg st, kiss_fft_scalar *X);
void kiss_fftri(kiss_fftr_cfg st,const kiss_fft_scalar *freqdata, kiss_fft_scalar *timedata);
/*
input freqdata has nfft/2+1 complex points, packed into nfft scalar points
output timedata has nfft scalar points
*/
#define kiss_fftr_free speex_free
#ifdef __cplusplus
}
#endif
#endif

141
fmod/lib/libcelt/laplace.c Executable file
View file

@ -0,0 +1,141 @@
/* (C) 2007 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "laplace.h"
int ec_laplace_get_start_freq(int decay)
{
int fs = (((ec_uint32)32768)*(16384-decay))/(16384+decay);
/* Making fs even so we're sure that all the range is used for +/- values */
fs -= (fs&1);
return fs;
}
#ifdef FMOD_CELT_ENCODER
void ec_laplace_encode_start(ec_enc *enc, int *value, int decay, int fs)
{
int i;
int fl;
unsigned int ft;
int s = 0;
int val = *value;
if (val < 0)
{
s = 1;
val = -val;
}
ft = 32768;
fl = -fs;
for (i=0;i<val;i++)
{
int tmp_l, tmp_s;
tmp_l = fl;
tmp_s = fs;
fl += fs*2;
fs = (fs*(ec_int32)decay)>>14;
if (fs == 0)
{
if (fl+2 <= ft)
{
fs = 1;
} else {
fs = tmp_s;
fl = tmp_l;
if (s)
*value = -i;
else
*value = i;
break;
}
}
}
if (fl < 0)
fl = 0;
if (s)
fl += fs;
ec_encode(enc, fl, fl+fs, ft);
}
void ec_laplace_encode(ec_enc *enc, int *value, int decay)
{
int fs = ec_laplace_get_start_freq(decay);
ec_laplace_encode_start(enc, value, decay, fs);
}
#endif
int ec_laplace_decode_start(ec_dec *dec, int decay, int fs)
{
int val=0;
int fl, fh, fm;
unsigned int ft;
fl = 0;
ft = 32768;
fh = fs;
fm = ec_decode(dec, ft);
while (fm >= fh && fs != 0)
{
fl = fh;
fs = (fs*(ec_int32)decay)>>14;
if (fs == 0 && fh+2 <= ft)
{
fs = 1;
}
fh += fs*2;
val++;
}
if (fl>0)
{
if (fm >= fl+fs)
{
val = -val;
fl += fs;
} else {
fh -= fs;
}
}
/* Preventing an infinite loop in case something screws up in the decoding */
if (fl==fh)
fl--;
ec_dec_update(dec, fl, fh, ft);
return val;
}
int ec_laplace_decode(ec_dec *dec, int decay)
{
int fs = ec_laplace_get_start_freq(decay);
return ec_laplace_decode_start(dec, decay, fs);
}

55
fmod/lib/libcelt/laplace.h Executable file
View file

@ -0,0 +1,55 @@
/* (C) 2007 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "entenc.h"
#include "entdec.h"
int ec_laplace_get_start_freq(int decay);
/** Encode a value that is assumed to be the realisation of a
Laplace-distributed random process
@param enc Entropy encoder state
@param value Value to encode
@param decay Probability of the value +/- 1, multiplied by 16384
*/
void ec_laplace_encode(ec_enc *enc, int *value, int decay);
void ec_laplace_encode_start(ec_enc *enc, int *value, int decay, int fs);
/** Decode a value that is assumed to be the realisation of a
Laplace-distributed random process
@param dec Entropy decoder state
@param decay Probability of the value +/- 1, multiplied by 16384
@return Value decoded
*/
int ec_laplace_decode(ec_dec *dec, int decay);
int ec_laplace_decode_start(ec_dec *dec, int decay, int fs);

371
fmod/lib/libcelt/mathops.h Executable file
View file

@ -0,0 +1,371 @@
/* Copyright (C) 2002-2008 Jean-Marc Valin */
/**
@file mathops.h
@brief Various math functions
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MATHOPS_H
#define MATHOPS_H
#include "arch.h"
#include "entcode.h"
#include "os_support.h"
#ifndef OVERRIDE_CELT_ILOG2
/** Integer log in base2. Undefined for zero and negative numbers */
static FMOD_INLINE celt_int16_t celt_ilog2(celt_word32_t x)
{
celt_assert2(x>0, "celt_ilog2() only defined for strictly positive numbers");
return EC_ILOG(x)-1;
}
#endif
#ifndef OVERRIDE_FIND_MAX16
static FMOD_INLINE int find_max16(celt_word16_t *x, int len)
{
celt_word16_t max_corr=-VERY_LARGE16;
int i, id = 0;
for (i=0;i<len;i++)
{
if (x[i] > max_corr)
{
id = i;
max_corr = x[i];
}
}
return id;
}
#endif
#ifndef OVERRIDE_FIND_MAX32
static FMOD_INLINE int find_max32(celt_word32_t *x, int len)
{
celt_word32_t max_corr=-VERY_LARGE32;
int i, id = 0;
for (i=0;i<len;i++)
{
if (x[i] > max_corr)
{
id = i;
max_corr = x[i];
}
}
return id;
}
#endif
#define FRAC_MUL16(a,b) ((16384+((celt_int32_t)(celt_int16_t)(a)*(celt_int16_t)(b)))>>15)
static FMOD_INLINE celt_int16_t bitexact_cos(celt_int16_t x)
{
celt_int32_t tmp;
celt_int16_t x2;
tmp = (4096+((celt_int32_t)(x)*(x)))>>13;
if (tmp > 32767)
tmp = 32767;
x2 = tmp;
x2 = (32767-x2) + FRAC_MUL16(x2, (-7651 + FRAC_MUL16(x2, (8277 + FRAC_MUL16(-626, x2)))));
if (x2 > 32766)
x2 = 32766;
return 1+x2;
}
#ifndef FIXED_POINT
#define celt_sqrt(x) ((float)sqrt(x))
#define celt_psqrt(x) ((float)sqrt(x))
#define celt_rsqrt(x) (1.f/celt_sqrt(x))
#define celt_acos acos
#define celt_exp exp
#define celt_cos_norm(x) (cos((.5f*M_PI)*(x)))
#define celt_atan atan
#define celt_rcp(x) (1.f/(x))
#define celt_div(a,b) ((a)/(b))
#ifdef FLOAT_APPROX
/* Note: This assumes radix-2 floating point with the exponent at bits 23..30 and an offset of 127
denorm, +/- inf and NaN are *not* handled */
/** Base-2 log approximation (log2(x)). */
static inline float celt_log2(float x)
{
int integer;
float frac;
union {
float f;
celt_uint32_t i;
} in;
in.f = x;
integer = (in.i>>23)-127;
in.i -= integer<<23;
frac = in.f - 1.5;
/* -0.41446 0.96093 -0.33981 0.15600 */
frac = -0.41446 + frac*(0.96093 + frac*(-0.33981 + frac*0.15600));
return 1+integer+frac;
}
/** Base-2 exponential approximation (2^x). */
static inline float celt_exp2(float x)
{
int integer;
float frac;
union {
float f;
celt_uint32_t i;
} res;
integer = floor(x);
if (integer < -50)
return 0;
frac = x-integer;
/* K0 = 1, K1 = log(2), K2 = 3-4*log(2), K3 = 3*log(2) - 2 */
res.f = 1.f + frac * (0.696147f + frac * (0.224411f + 0.079442f*frac));
res.i = (res.i + (integer<<23)) & 0x7fffffff;
return res.f;
}
#else
#define celt_log2(x) (1.442695040888963387*log(x))
#define celt_exp2(x) (exp(0.6931471805599453094*(x)))
#endif
#endif
#ifdef FIXED_POINT
#include "os_support.h"
#ifndef OVERRIDE_CELT_MAXABS16
static inline celt_word16_t celt_maxabs16(celt_word16_t *x, int len)
{
int i;
celt_word16_t maxval = 0;
for (i=0;i<len;i++)
maxval = MAX16(maxval, ABS16(x[i]));
return maxval;
}
#endif
/** Integer log in base2. Defined for zero, but not for negative numbers */
static inline celt_int16_t celt_zlog2(celt_word32_t x)
{
return x <= 0 ? 0 : celt_ilog2(x);
}
/** Reciprocal sqrt approximation (Q30 input, Q0 output or equivalent) */
static inline celt_word32_t celt_rsqrt(celt_word32_t x)
{
int k;
celt_word16_t n;
celt_word32_t rt;
const celt_word16_t C[5] = {23126, -11496, 9812, -9097, 4100};
k = celt_ilog2(x)>>1;
x = VSHR32(x, (k-7)<<1);
/* Range of n is [-16384,32767] */
n = x-32768;
rt = ADD16(C[0], MULT16_16_Q15(n, ADD16(C[1], MULT16_16_Q15(n, ADD16(C[2],
MULT16_16_Q15(n, ADD16(C[3], MULT16_16_Q15(n, (C[4])))))))));
rt = VSHR32(rt,k);
return rt;
}
/** Sqrt approximation (QX input, QX/2 output) */
static inline celt_word32_t celt_sqrt(celt_word32_t x)
{
int k;
celt_word16_t n;
celt_word32_t rt;
const celt_word16_t C[5] = {23174, 11584, -3011, 1570, -557};
if (x==0)
return 0;
k = (celt_ilog2(x)>>1)-7;
x = VSHR32(x, (k<<1));
n = x-32768;
rt = ADD16(C[0], MULT16_16_Q15(n, ADD16(C[1], MULT16_16_Q15(n, ADD16(C[2],
MULT16_16_Q15(n, ADD16(C[3], MULT16_16_Q15(n, (C[4])))))))));
rt = VSHR32(rt,7-k);
return rt;
}
/** Sqrt approximation (QX input, QX/2 output) that assumes that the input is
strictly positive */
static inline celt_word32_t celt_psqrt(celt_word32_t x)
{
int k;
celt_word16_t n;
celt_word32_t rt;
const celt_word16_t C[5] = {23174, 11584, -3011, 1570, -557};
k = (celt_ilog2(x)>>1)-7;
x = VSHR32(x, (k<<1));
n = x-32768;
rt = ADD16(C[0], MULT16_16_Q15(n, ADD16(C[1], MULT16_16_Q15(n, ADD16(C[2],
MULT16_16_Q15(n, ADD16(C[3], MULT16_16_Q15(n, (C[4])))))))));
rt = VSHR32(rt,7-k);
return rt;
}
#define L1 32767
#define L2 -7651
#define L3 8277
#define L4 -626
static inline celt_word16_t _celt_cos_pi_2(celt_word16_t x)
{
celt_word16_t x2;
x2 = MULT16_16_P15(x,x);
return ADD16(1,MIN16(32766,ADD32(SUB16(L1,x2), MULT16_16_P15(x2, ADD32(L2, MULT16_16_P15(x2, ADD32(L3, MULT16_16_P15(L4, x2
))))))));
}
#undef L1
#undef L2
#undef L3
#undef L4
static inline celt_word16_t celt_cos_norm(celt_word32_t x)
{
x = x&0x0001ffff;
if (x>SHL32(EXTEND32(1), 16))
x = SUB32(SHL32(EXTEND32(1), 17),x);
if (x&0x00007fff)
{
if (x<SHL32(EXTEND32(1), 15))
{
return _celt_cos_pi_2(EXTRACT16(x));
} else {
return NEG32(_celt_cos_pi_2(EXTRACT16(65536-x)));
}
} else {
if (x&0x0000ffff)
return 0;
else if (x&0x0001ffff)
return -32767;
else
return 32767;
}
}
static inline celt_word16_t celt_log2(celt_word32_t x)
{
int i;
celt_word16_t n, frac;
/*-0.41446 0.96093 -0.33981 0.15600 */
const celt_word16_t C[4] = {-6791, 7872, -1392, 319};
if (x==0)
return -32767;
i = celt_ilog2(x);
n = VSHR32(x,i-15)-32768-16384;
frac = ADD16(C[0], MULT16_16_Q14(n, ADD16(C[1], MULT16_16_Q14(n, ADD16(C[2], MULT16_16_Q14(n, (C[3])))))));
return SHL16(i-13,8)+SHR16(frac,14-8);
}
/*
K0 = 1
K1 = log(2)
K2 = 3-4*log(2)
K3 = 3*log(2) - 2
*/
#define D0 16384
#define D1 11356
#define D2 3726
#define D3 1301
/** Base-2 exponential approximation (2^x). (Q11 input, Q16 output) */
static inline celt_word32_t celt_exp2(celt_word16_t x)
{
int integer;
celt_word16_t frac;
integer = SHR16(x,11);
if (integer>14)
return 0x7f000000;
else if (integer < -15)
return 0;
frac = SHL16(x-SHL16(integer,11),3);
frac = ADD16(D0, MULT16_16_Q14(frac, ADD16(D1, MULT16_16_Q14(frac, ADD16(D2 , MULT16_16_Q14(D3,frac))))));
return VSHR32(EXTEND32(frac), -integer-2);
}
/** Reciprocal approximation (Q15 input, Q16 output) */
static inline celt_word32_t celt_rcp(celt_word32_t x)
{
int i;
celt_word16_t n, frac;
const celt_word16_t C[5] = {21848, -7251, 2403, -934, 327};
celt_assert2(x>0, "celt_rcp() only defined for positive values");
i = celt_ilog2(x);
n = VSHR32(x,i-16)-SHL32(EXTEND32(3),15);
frac = ADD16(C[0], MULT16_16_Q15(n, ADD16(C[1], MULT16_16_Q15(n, ADD16(C[2],
MULT16_16_Q15(n, ADD16(C[3], MULT16_16_Q15(n, (C[4])))))))));
return VSHR32(EXTEND32(frac),i-16);
}
#define celt_div(a,b) MULT32_32_Q31((celt_word32_t)(a),celt_rcp(b))
#define M1 32767
#define M2 -21
#define M3 -11943
#define M4 4936
static inline celt_word16_t celt_atan01(celt_word16_t x)
{
return MULT16_16_P15(x, ADD32(M1, MULT16_16_P15(x, ADD32(M2, MULT16_16_P15(x, ADD32(M3, MULT16_16_P15(M4, x)))))));
}
#undef M1
#undef M2
#undef M3
#undef M4
static inline celt_word16_t celt_atan2p(celt_word16_t y, celt_word16_t x)
{
if (y < x)
{
celt_word32_t arg;
arg = celt_div(SHL32(EXTEND32(y),15),x);
if (arg >= 32767)
arg = 32767;
return SHR16(celt_atan01(EXTRACT16(arg)),1);
} else {
celt_word32_t arg;
arg = celt_div(SHL32(EXTEND32(x),15),y);
if (arg >= 32767)
arg = 32767;
return 25736-SHR16(celt_atan01(EXTRACT16(arg)),1);
}
}
#endif /* FIXED_POINT */
#endif /* MATHOPS_H */

295
fmod/lib/libcelt/mdct.c Executable file
View file

@ -0,0 +1,295 @@
/* (C) 2008 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* This is a simple MDCT implementation that uses a N/4 complex FFT
to do most of the work. It should be relatively straightforward to
plug in pretty much and FFT here.
This replaces the Vorbis FFT (and uses the exact same API), which
was a bit too messy and that was ending up duplicating code
(might as well use the same FFT everywhere).
The algorithm is similar to (and inspired from) Fabrice Bellard's
MDCT implementation in FFMPEG, but has differences in signs, ordering
and scaling in many places.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "mdct.h"
#include "kfft_double.h"
#include <math.h>
#include "os_support.h"
#include "mathops.h"
#include "stack_alloc.h"
#ifndef M_PI
#define M_PI 3.141592653
#endif
void mdct_init(mdct_lookup *l,int N)
{
int i;
int N2;
l->n = N;
N2 = N>>1;
l->kfft = cpx32_fft_alloc(N>>2);
if (l->kfft==NULL)
return;
l->trig = (kiss_twiddle_scalar*)celt_alloc(N2*sizeof(kiss_twiddle_scalar));
if (l->trig==NULL)
return;
/* We have enough points that sine isn't necessary */
#if defined(FIXED_POINT)
#if defined(DOUBLE_PRECISION) & !defined(MIXED_PRECISION)
for (i=0;i<N2;i++)
l->trig[i] = SAMP_MAX*cos(2*M_PI*(i+1./8.)/N);
#else
for (i=0;i<N2;i++)
l->trig[i] = TRIG_UPSCALE*celt_cos_norm(DIV32(ADD32(SHL32(EXTEND32(i),17),16386),N));
#endif
#else
for (i=0;i<N2;i++)
l->trig[i] = cos(2*M_PI*(i+1./8.)/N);
#endif
}
void mdct_clear(mdct_lookup *l)
{
cpx32_fft_free(l->kfft);
celt_free(l->trig);
}
void mdct_forward(const mdct_lookup *l, kiss_fft_scalar *in, kiss_fft_scalar * celt_restrict out, const celt_word16_t *window, int overlap)
{
int i;
int N, N2, N4;
VARDECL(kiss_fft_scalar, f);
SAVE_STACK;
N = l->n;
N2 = N>>1;
N4 = N>>2;
ALLOC(f, N2, kiss_fft_scalar);
/* Consider the input to be compused of four blocks: [a, b, c, d] */
/* Window, shuffle, fold */
{
/* Temp pointers to make it really clear to the compiler what we're doing */
const kiss_fft_scalar * celt_restrict xp1 = in+(overlap>>1);
const kiss_fft_scalar * celt_restrict xp2 = in+N2-1+(overlap>>1);
kiss_fft_scalar * celt_restrict yp = out;
const celt_word16_t * celt_restrict wp1 = window+(overlap>>1);
const celt_word16_t * celt_restrict wp2 = window+(overlap>>1)-1;
for(i=0;i<(overlap>>2);i++)
{
/* Real part arranged as -d-cR, Imag part arranged as -b+aR*/
*yp++ = MULT16_32_Q15(*wp2, xp1[N2]) + MULT16_32_Q15(*wp1,*xp2);
*yp++ = MULT16_32_Q15(*wp1, *xp1) - MULT16_32_Q15(*wp2, xp2[-N2]);
xp1+=2;
xp2-=2;
wp1+=2;
wp2-=2;
}
wp1 = window;
wp2 = window+overlap-1;
for(;i<N4-(overlap>>2);i++)
{
/* Real part arranged as a-bR, Imag part arranged as -c-dR */
*yp++ = *xp2;
*yp++ = *xp1;
xp1+=2;
xp2-=2;
}
for(;i<N4;i++)
{
/* Real part arranged as a-bR, Imag part arranged as -c-dR */
*yp++ = -MULT16_32_Q15(*wp1, xp1[-N2]) + MULT16_32_Q15(*wp2, *xp2);
*yp++ = MULT16_32_Q15(*wp2, *xp1) + MULT16_32_Q15(*wp1, xp2[N2]);
xp1+=2;
xp2-=2;
wp1+=2;
wp2-=2;
}
}
/* Pre-rotation */
{
kiss_fft_scalar * celt_restrict yp = out;
kiss_fft_scalar *t = &l->trig[0];
for(i=0;i<N4;i++)
{
kiss_fft_scalar re, im;
re = yp[0];
im = yp[1];
*yp++ = -S_MUL(re,t[0]) + S_MUL(im,t[N4]);
*yp++ = -S_MUL(im,t[0]) - S_MUL(re,t[N4]);
t++;
}
}
/* N/4 complex FFT, down-scales by 4/N */
cpx32_fft(l->kfft, out, f, N4);
/* Post-rotate */
{
/* Temp pointers to make it really clear to the compiler what we're doing */
const kiss_fft_scalar * celt_restrict fp = f;
kiss_fft_scalar * celt_restrict yp1 = out;
kiss_fft_scalar * celt_restrict yp2 = out+N2-1;
kiss_fft_scalar *t = &l->trig[0];
/* Temp pointers to make it really clear to the compiler what we're doing */
for(i=0;i<N4;i++)
{
*yp1 = -S_MUL(fp[1],t[N4]) + S_MUL(fp[0],t[0]);
*yp2 = -S_MUL(fp[0],t[N4]) - S_MUL(fp[1],t[0]);
fp += 2;
yp1 += 2;
yp2 -= 2;
t++;
}
}
RESTORE_STACK;
}
void mdct_backward(const mdct_lookup *l, kiss_fft_scalar *in, kiss_fft_scalar * celt_restrict out, const celt_word16_t * celt_restrict window, int overlap)
{
int i;
int N, N2, N4;
VARDECL(kiss_fft_scalar, f);
VARDECL(kiss_fft_scalar, f2);
SAVE_STACK;
N = l->n;
N2 = N>>1;
N4 = N>>2;
ALLOC(f, N2, kiss_fft_scalar);
ALLOC(f2, N2, kiss_fft_scalar);
/* Pre-rotate */
{
/* Temp pointers to make it really clear to the compiler what we're doing */
const kiss_fft_scalar * celt_restrict xp1 = in;
const kiss_fft_scalar * celt_restrict xp2 = in+N2-1;
kiss_fft_scalar * celt_restrict yp = f2;
kiss_fft_scalar *t = &l->trig[0];
for(i=0;i<N4;i++)
{
*yp++ = -S_MUL(*xp2, t[0]) - S_MUL(*xp1,t[N4]);
*yp++ = S_MUL(*xp2, t[N4]) - S_MUL(*xp1,t[0]);
xp1+=2;
xp2-=2;
t++;
}
}
/* Inverse N/4 complex FFT. This one should *not* downscale even in fixed-point */
cpx32_ifft(l->kfft, f2, f, N4);
/* Post-rotate */
{
kiss_fft_scalar * celt_restrict fp = f;
kiss_fft_scalar *t = &l->trig[0];
for(i=0;i<N4;i++)
{
kiss_fft_scalar re, im;
re = fp[0];
im = fp[1];
/* We'd scale up by 2 here, but instead it's done when mixing the windows */
*fp++ = S_MUL(re,*t) + S_MUL(im,t[N4]);
*fp++ = S_MUL(im,*t) - S_MUL(re,t[N4]);
t++;
}
}
/* De-shuffle the components for the middle of the window only */
{
const kiss_fft_scalar * celt_restrict fp1 = f;
const kiss_fft_scalar * celt_restrict fp2 = f+N2-1;
kiss_fft_scalar * celt_restrict yp = f2;
for(i = 0; i < N4; i++)
{
*yp++ =-*fp1;
*yp++ = *fp2;
fp1 += 2;
fp2 -= 2;
}
}
/* Mirror on both sides for TDAC */
{
kiss_fft_scalar * celt_restrict fp1 = f2+N4-1;
kiss_fft_scalar * celt_restrict xp1 = out+N2-1;
kiss_fft_scalar * celt_restrict yp1 = out+N4-overlap/2;
const celt_word16_t * celt_restrict wp1 = window;
const celt_word16_t * celt_restrict wp2 = window+overlap-1;
for(i = 0; i< N4-overlap/2; i++)
{
*xp1 = *fp1;
xp1--;
fp1--;
}
for(; i < N4; i++)
{
kiss_fft_scalar x1;
x1 = *fp1--;
*yp1++ +=-MULT16_32_Q15(*wp1, x1);
*xp1-- += MULT16_32_Q15(*wp2, x1);
wp1++;
wp2--;
}
}
{
kiss_fft_scalar * celt_restrict fp2 = f2+N4;
kiss_fft_scalar * celt_restrict xp2 = out+N2;
kiss_fft_scalar * celt_restrict yp2 = out+N-1-(N4-overlap/2);
const celt_word16_t * celt_restrict wp1 = window;
const celt_word16_t * celt_restrict wp2 = window+overlap-1;
for(i = 0; i< N4-overlap/2; i++)
{
*xp2 = *fp2;
xp2++;
fp2++;
}
for(; i < N4; i++)
{
kiss_fft_scalar x2;
x2 = *fp2++;
*yp2-- = MULT16_32_Q15(*wp1, x2);
*xp2++ = MULT16_32_Q15(*wp2, x2);
wp1++;
wp2--;
}
}
RESTORE_STACK;
}

67
fmod/lib/libcelt/mdct.h Executable file
View file

@ -0,0 +1,67 @@
/* (C) 2008 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* This is a simple MDCT implementation that uses a N/4 complex FFT
to do most of the work. It should be relatively straightforward to
plug in pretty much and FFT here.
This replaces the Vorbis FFT (and uses the exact same API), which
was a bit too messy and that was ending up duplicating code
(might as well use the same FFT everywhere).
The algorithm is similar to (and inspired from) Fabrice Bellard's
MDCT implementation in FFMPEG, but has differences in signs, ordering
and scaling in many places.
*/
#ifndef MDCT_H
#define MDCT_H
#include "kiss_fft.h"
#include "arch.h"
typedef struct {
int n;
kiss_fft_cfg kfft;
kiss_twiddle_scalar * celt_restrict trig;
} mdct_lookup;
void mdct_init(mdct_lookup *l,int N);
void mdct_clear(mdct_lookup *l);
/** Compute a forward MDCT and scale by 4/N */
void mdct_forward(const mdct_lookup *l, kiss_fft_scalar *in, kiss_fft_scalar * celt_restrict out, const celt_word16_t *window, int overlap);
/** Compute a backward MDCT (no scaling) and performs weighted overlap-add
(scales implicitly by 1/2) */
void mdct_backward(const mdct_lookup *l, kiss_fft_scalar *in, kiss_fft_scalar * celt_restrict out, const celt_word16_t * celt_restrict window, int overlap);
#endif

60
fmod/lib/libcelt/mfrngcod.h Executable file
View file

@ -0,0 +1,60 @@
/* (C) 2001-2008 Timothy B. Terriberry
(C) 2008 Jean-Marc Valin */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if !defined(_mfrngcode_H)
# define _mfrngcode_H (1)
# include "entcode.h"
/*Constants used by the entropy encoder/decoder.*/
/*The number of bits to output at a time.*/
# define EC_SYM_BITS (8)
/*The total number of bits in each of the state registers.*/
# define EC_CODE_BITS (32)
/*The maximum symbol value.*/
# define EC_SYM_MAX ((1U<<EC_SYM_BITS)-1)
/*Bits to shift by to move a symbol into the high-order position.*/
# define EC_CODE_SHIFT (EC_CODE_BITS-EC_SYM_BITS-1)
/*Carry bit of the high-order range symbol.*/
# define EC_CODE_TOP (((ec_uint32)1U)<<EC_CODE_BITS-1)
/*Low-order bit of the high-order range symbol.*/
# define EC_CODE_BOT (EC_CODE_TOP>>EC_SYM_BITS)
/*Code for which propagating carries are possible.*/
# define EC_CODE_CARRY (((ec_uint32)EC_SYM_MAX)<<EC_CODE_SHIFT)
/*The number of bits available for the last, partial symbol in the code field.*/
# define EC_CODE_EXTRA ((EC_CODE_BITS-2)%EC_SYM_BITS+1)
/*A mask for the bits available in the coding buffer.
This allows different platforms to use a variable with more bits, if it is
convenient.
We will only use EC_CODE_BITS of it.*/
# define EC_CODE_MASK ((((ec_uint32)1U)<<EC_CODE_BITS-1)-1<<1|1)
#endif

514
fmod/lib/libcelt/modes.c Executable file
View file

@ -0,0 +1,514 @@
/* (C) 2007-2009 Jean-Marc Valin, CSIRO
(C) 2008 Gregory Maxwell */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "celt.h"
#include "modes.h"
#include "rate.h"
#include "os_support.h"
#include "stack_alloc.h"
#include "quant_bands.h"
#ifdef STATIC_MODES
#include "static_modes.c"
#endif
#define MODEVALID 0xa110ca7e
#define MODEPARTIAL 0x7eca10a1
#define MODEFREED 0xb10cf8ee
#ifndef M_PI
#define M_PI 3.141592653
#endif
int celt_mode_info(const CELTMode *mode, int request, celt_int32_t *value)
{
if (check_mode(mode) != CELT_OK)
return CELT_INVALID_MODE;
switch (request)
{
case CELT_GET_FRAME_SIZE:
*value = mode->mdctSize;
break;
case CELT_GET_LOOKAHEAD:
*value = mode->overlap;
break;
case CELT_GET_NB_CHANNELS:
*value = mode->nbChannels;
break;
case CELT_GET_BITSTREAM_VERSION:
*value = CELT_BITSTREAM_VERSION;
break;
case CELT_GET_SAMPLE_RATE:
*value = mode->Fs;
break;
default:
return CELT_UNIMPLEMENTED;
}
return CELT_OK;
}
#ifndef STATIC_MODES
#define PBANDS 8
#ifdef STDIN_TUNING
int MIN_BINS;
#else
#define MIN_BINS 3
#endif
/* Defining 25 critical bands for the full 0-20 kHz audio bandwidth
Taken from http://ccrma.stanford.edu/~jos/bbt/Bark_Frequency_Scale.html */
#define BARK_BANDS 25
static const celt_int16_t bark_freq[BARK_BANDS+1] = {
0, 100, 200, 300, 400,
510, 630, 770, 920, 1080,
1270, 1480, 1720, 2000, 2320,
2700, 3150, 3700, 4400, 5300,
6400, 7700, 9500, 12000, 15500,
20000};
static const celt_int16_t pitch_freq[PBANDS+1] ={0, 345, 689, 1034, 1378, 2067, 3273, 5340, 6374};
/* This allocation table is per critical band. When creating a mode, the bits get added together
into the codec bands, which are sometimes larger than one critical band at low frequency */
#ifdef STDIN_TUNING
int BITALLOC_SIZE;
int *band_allocation;
#else
#define BITALLOC_SIZE 12
static const int band_allocation[BARK_BANDS*BITALLOC_SIZE] =
/* 0 100 200 300 400 510 630 770 920 1k 1.2 1.5 1.7 2k 2.3 2.7 3.1 3.7 4.4 5.3 6.4 7.7 9.5 12k 15k */
{ 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*0*/
2, 2, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*1*/
2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 4, 5, 7, 7, 7, 5, 4, 0, 0, 0, 0, 0, 0, /*2*/
2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 5, 6, 8, 8, 8, 6, 5, 4, 0, 0, 0, 0, 0, /*3*/
3, 2, 2, 2, 3, 4, 4, 4, 4, 4, 4, 4, 6, 7, 9, 9, 9, 7, 6, 5, 5, 5, 0, 0, 0, /*4*/
3, 3, 3, 4, 4, 5, 6, 6, 6, 6, 6, 7, 7, 9, 10, 10, 10, 9, 6, 5, 5, 5, 5, 1, 0, /*5*/
4, 3, 3, 4, 6, 7, 7, 7, 7, 7, 8, 9, 9, 9, 11, 10, 10, 9, 9, 8, 11, 10, 10, 1, 0, /*6*/
5, 5, 5, 6, 7, 7, 7, 7, 8, 8, 9, 10, 10, 12, 12, 11, 11, 17, 12, 15, 15, 20, 18, 10, 1, /*7*/
6, 7, 7, 7, 8, 8, 8, 8, 9, 10, 11, 12, 14, 17, 18, 21, 22, 27, 29, 39, 37, 38, 40, 35, 1, /*8*/
7, 7, 7, 8, 8, 8, 10, 10, 10, 13, 14, 18, 20, 24, 28, 32, 32, 35, 38, 38, 42, 50, 59, 54, 31, /*9*/
8, 8, 8, 8, 8, 9, 10, 12, 14, 20, 22, 25, 28, 30, 35, 42, 46, 50, 55, 60, 62, 62, 72, 82, 62, /*10*/
9, 9, 9, 10, 12, 13, 15, 18, 22, 30, 32, 35, 40, 45, 55, 62, 66, 70, 85, 90, 92, 92, 92,102, 92, /*11*/
};
#endif
static celt_int16_t *compute_ebands(celt_int32_t Fs, int frame_size, int *nbEBands)
{
celt_int16_t *eBands;
int i, res, min_width, lin, low, high, nBark;
res = (Fs+frame_size)/(2*frame_size);
min_width = MIN_BINS*res;
/* Find the number of critical bands supported by our sampling rate */
for (nBark=1;nBark<BARK_BANDS;nBark++)
if (bark_freq[nBark+1]*2 >= Fs)
break;
/* Find where the linear part ends (i.e. where the spacing is more than min_width */
for (lin=0;lin<nBark;lin++)
if (bark_freq[lin+1]-bark_freq[lin] >= min_width)
break;
low = ((bark_freq[lin]/res)+(MIN_BINS-1))/MIN_BINS;
high = nBark-lin;
*nbEBands = low+high;
eBands = celt_alloc(sizeof(celt_int16_t)*(*nbEBands+2));
if (eBands==NULL)
return NULL;
/* Linear spacing (min_width) */
for (i=0;i<low;i++)
eBands[i] = MIN_BINS*i;
/* Spacing follows critical bands */
for (i=0;i<high;i++)
eBands[i+low] = (bark_freq[lin+i]+res/2)/res;
/* Enforce the minimum spacing at the boundary */
for (i=0;i<*nbEBands;i++)
if (eBands[i] < MIN_BINS*i)
eBands[i] = MIN_BINS*i;
eBands[*nbEBands] = (bark_freq[nBark]+res/2)/res;
eBands[*nbEBands+1] = frame_size;
if (eBands[*nbEBands] > eBands[*nbEBands+1])
eBands[*nbEBands] = eBands[*nbEBands+1];
/* FIXME: Remove last band if too small */
return eBands;
}
static void compute_pbands(CELTMode *mode, int res)
{
int i;
celt_int16_t *pBands;
pBands=celt_alloc(sizeof(celt_int16_t)*(PBANDS+2));
mode->pBands = pBands;
if (pBands==NULL)
return;
mode->nbPBands = PBANDS;
for (i=0;i<PBANDS+1;i++)
{
pBands[i] = (pitch_freq[i]+res/2)/res;
if (pBands[i] < mode->eBands[i])
pBands[i] = mode->eBands[i];
}
pBands[PBANDS+1] = mode->eBands[mode->nbEBands+1];
for (i=1;i<mode->nbPBands+1;i++)
{
int j;
for (j=0;j<mode->nbEBands;j++)
if (mode->eBands[j] <= pBands[i] && mode->eBands[j+1] > pBands[i])
break;
if (mode->eBands[j] != pBands[i])
{
if (pBands[i]-mode->eBands[j] < mode->eBands[j+1]-pBands[i] &&
mode->eBands[j] != pBands[i-1])
pBands[i] = mode->eBands[j];
else
pBands[i] = mode->eBands[j+1];
}
}
mode->pitchEnd = pBands[PBANDS];
}
static void compute_allocation_table(CELTMode *mode, int res)
{
int i, j, nBark;
celt_int16_t *allocVectors;
const int C = CHANNELS(mode);
/* Find the number of critical bands supported by our sampling rate */
for (nBark=1;nBark<BARK_BANDS;nBark++)
if (bark_freq[nBark+1]*2 >= mode->Fs)
break;
mode->nbAllocVectors = BITALLOC_SIZE;
allocVectors = celt_alloc(sizeof(celt_int16_t)*(BITALLOC_SIZE*mode->nbEBands));
if (allocVectors==NULL)
return;
/* Compute per-codec-band allocation from per-critical-band matrix */
for (i=0;i<BITALLOC_SIZE;i++)
{
celt_int32_t current = 0;
int eband = 0;
for (j=0;j<nBark;j++)
{
int edge, low;
celt_int32_t alloc;
edge = mode->eBands[eband+1]*res;
alloc = band_allocation[i*BARK_BANDS+j];
alloc = alloc*C*mode->mdctSize;
if (edge < bark_freq[j+1])
{
int num, den;
num = alloc * (edge-bark_freq[j]);
den = bark_freq[j+1]-bark_freq[j];
low = (num+den/2)/den;
allocVectors[i*mode->nbEBands+eband] = (current+low+128)/256;
current=0;
eband++;
current += alloc-low;
} else {
current += alloc;
}
}
allocVectors[i*mode->nbEBands+eband] = (current+128)/256;
}
mode->allocVectors = allocVectors;
}
#endif /* STATIC_MODES */
CELTMode *celt_mode_create(celt_int32_t Fs, int channels, int frame_size, int *error)
{
int i;
#ifdef STDIN_TUNING
scanf("%d ", &MIN_BINS);
scanf("%d ", &BITALLOC_SIZE);
band_allocation = celt_alloc(sizeof(int)*BARK_BANDS*BITALLOC_SIZE);
for (i=0;i<BARK_BANDS*BITALLOC_SIZE;i++)
{
scanf("%d ", band_allocation+i);
}
#endif
#ifdef STATIC_MODES
const CELTMode *m = NULL;
CELTMode *mode=NULL;
ALLOC_STACK;
#if !defined(VAR_ARRAYS) && !defined(USE_ALLOCA)
if (global_stack==NULL)
{
celt_free(global_stack);
goto failure;
}
#endif
for (i=0;i<TOTAL_MODES;i++)
{
if (Fs == static_mode_list[i]->Fs &&
channels == static_mode_list[i]->nbChannels &&
frame_size == static_mode_list[i]->mdctSize)
{
m = static_mode_list[i];
break;
}
}
if (m == NULL)
{
celt_warning("Mode not included as part of the static modes");
if (error)
*error = CELT_BAD_ARG;
return NULL;
}
mode = (CELTMode*)celt_alloc(sizeof(CELTMode));
if (mode==NULL)
goto failure;
CELT_COPY(mode, m, 1);
mode->marker_start = MODEPARTIAL;
#else
int res;
CELTMode *mode=NULL;
celt_word16_t *window;
ALLOC_STACK;
#if !defined(VAR_ARRAYS) && !defined(USE_ALLOCA)
if (global_stack==NULL)
{
celt_free(global_stack);
goto failure;
}
#endif
/* The good thing here is that permutation of the arguments will automatically be invalid */
if (Fs < 32000 || Fs > 96000)
{
celt_warning("Sampling rate must be between 32 kHz and 96 kHz");
if (error)
*error = CELT_BAD_ARG;
return NULL;
}
if (channels < 0 || channels > 2)
{
celt_warning("Only mono and stereo supported");
if (error)
*error = CELT_BAD_ARG;
return NULL;
}
if (frame_size < 64 || frame_size > 1024 || frame_size%2!=0)
{
celt_warning("Only even frame sizes from 64 to 1024 are supported");
if (error)
*error = CELT_BAD_ARG;
return NULL;
}
res = (Fs+frame_size)/(2*frame_size);
mode = celt_alloc(sizeof(CELTMode));
if (mode==NULL)
goto failure;
mode->marker_start = MODEPARTIAL;
mode->Fs = Fs;
mode->mdctSize = frame_size;
mode->nbChannels = channels;
mode->eBands = compute_ebands(Fs, frame_size, &mode->nbEBands);
if (mode->eBands==NULL)
goto failure;
compute_pbands(mode, res);
if (mode->pBands==NULL)
goto failure;
mode->ePredCoef = QCONST16(.8f,15);
if (frame_size > 640 && (frame_size%16)==0)
{
mode->nbShortMdcts = 8;
} else if (frame_size > 384 && (frame_size%8)==0)
{
mode->nbShortMdcts = 4;
} else if (frame_size > 384 && (frame_size%10)==0)
{
mode->nbShortMdcts = 5;
} else if (frame_size > 256 && (frame_size%6)==0)
{
mode->nbShortMdcts = 3;
} else if (frame_size > 256 && (frame_size%8)==0)
{
mode->nbShortMdcts = 4;
} else if (frame_size > 64 && (frame_size%4)==0)
{
mode->nbShortMdcts = 2;
} else if (frame_size > 128 && (frame_size%6)==0)
{
mode->nbShortMdcts = 3;
} else
{
mode->nbShortMdcts = 1;
}
/* Overlap must be divisible by 4 */
if (mode->nbShortMdcts > 1)
mode->overlap = ((frame_size/mode->nbShortMdcts)>>2)<<2;
else
mode->overlap = (frame_size>>3)<<2;
compute_allocation_table(mode, res);
if (mode->allocVectors==NULL)
goto failure;
window = (celt_word16_t*)celt_alloc(mode->overlap*sizeof(celt_word16_t));
if (window==NULL)
goto failure;
#ifndef FIXED_POINT
for (i=0;i<mode->overlap;i++)
window[i] = Q15ONE*sin(.5*M_PI* sin(.5*M_PI*(i+.5)/mode->overlap) * sin(.5*M_PI*(i+.5)/mode->overlap));
#else
for (i=0;i<mode->overlap;i++)
window[i] = MIN32(32767,32768.*sin(.5*M_PI* sin(.5*M_PI*(i+.5)/mode->overlap) * sin(.5*M_PI*(i+.5)/mode->overlap)));
#endif
mode->window = window;
mode->bits = (const celt_int16_t **)compute_alloc_cache(mode, 1);
if (mode->bits==NULL)
goto failure;
#ifndef SHORTCUTS
psydecay_init(&mode->psy, MAX_PERIOD/2, mode->Fs);
if (mode->psy.decayR==NULL)
goto failure;
#endif
#endif /* !STATIC_MODES */
#ifdef DISABLE_STEREO
if (channels > 1)
{
celt_warning("Stereo support was disable from this build");
if (error)
*error = CELT_BAD_ARG;
return NULL;
}
#endif
mdct_init(&mode->mdct, 2*mode->mdctSize);
mode->fft = pitch_state_alloc(MAX_PERIOD);
mode->shortMdctSize = mode->mdctSize/mode->nbShortMdcts;
mdct_init(&mode->shortMdct, 2*mode->shortMdctSize);
mode->shortWindow = mode->window;
mode->prob = quant_prob_alloc(mode);
if ((mode->mdct.trig==NULL) || (mode->mdct.kfft==NULL) || (mode->fft==NULL) ||
(mode->shortMdct.trig==NULL) || (mode->shortMdct.kfft==NULL) || (mode->prob==NULL))
goto failure;
mode->marker_start = MODEVALID;
mode->marker_end = MODEVALID;
if (error)
*error = CELT_OK;
return mode;
failure:
if (error)
*error = CELT_INVALID_MODE;
if (mode!=NULL)
celt_mode_destroy(mode);
return NULL;
}
void celt_mode_destroy(CELTMode *mode)
{
int i;
const celt_int16_t *prevPtr = NULL;
if (mode == NULL)
{
celt_warning("NULL passed to celt_mode_destroy");
return;
}
if (mode->marker_start == MODEFREED || mode->marker_end == MODEFREED)
{
celt_warning("Freeing a mode which has already been freed");
return;
}
if (mode->marker_start != MODEVALID && mode->marker_start != MODEPARTIAL)
{
celt_warning("This is not a valid CELT mode structure");
return;
}
mode->marker_start = MODEFREED;
#ifndef STATIC_MODES
if (mode->bits!=NULL)
{
for (i=0;i<mode->nbEBands;i++)
{
if (mode->bits[i] != prevPtr)
{
prevPtr = mode->bits[i];
celt_free((int*)mode->bits[i]);
}
}
}
celt_free((int**)mode->bits);
celt_free((int*)mode->eBands);
celt_free((int*)mode->pBands);
celt_free((int*)mode->allocVectors);
celt_free((celt_word16_t*)mode->window);
#ifndef SHORTCUTS
psydecay_clear(&mode->psy);
#endif
#endif
mdct_clear(&mode->mdct);
mdct_clear(&mode->shortMdct);
pitch_state_free(mode->fft);
quant_prob_free(mode->prob);
mode->marker_end = MODEFREED;
celt_free((CELTMode *)mode);
}
int check_mode(const CELTMode *mode)
{
if (mode==NULL)
return CELT_INVALID_MODE;
if (mode->marker_start == MODEVALID && mode->marker_end == MODEVALID)
return CELT_OK;
if (mode->marker_start == MODEFREED || mode->marker_end == MODEFREED)
celt_warning("Using a mode that has already been freed");
else
celt_warning("This is not a valid CELT mode");
return CELT_INVALID_MODE;
}

111
fmod/lib/libcelt/modes.h Executable file
View file

@ -0,0 +1,111 @@
/* (C) 2007-2008 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MODES_H
#define MODES_H
#include "celt_types.h"
#include "celt.h"
#include "arch.h"
#include "mdct.h"
#include "psy.h"
#include "pitch.h"
#define CELT_BITSTREAM_VERSION 0x80000009
#ifdef STATIC_MODES
#include "static_modes.h"
#endif
#define MAX_PERIOD 512
#ifndef CHANNELS
# ifdef DISABLE_STEREO
# define CHANNELS(mode) (1)
# else
# define CHANNELS(mode) ((mode)->nbChannels)
# endif
#endif
#define MDCT(mode) (&(mode)->mdct)
#ifndef OVERLAP
#define OVERLAP(mode) ((mode)->overlap)
#endif
#ifndef FRAMESIZE
#define FRAMESIZE(mode) ((mode)->mdctSize)
#endif
/** Mode definition (opaque)
@brief Mode definition
*/
struct CELTMode {
celt_uint32_t marker_start;
celt_int32_t Fs;
int overlap;
int mdctSize;
int nbChannels;
int nbEBands;
int nbPBands;
int pitchEnd;
const celt_int16_t *eBands; /**< Definition for each "pseudo-critical band" */
const celt_int16_t *pBands; /**< Definition of the bands used for the pitch */
celt_word16_t ePredCoef;/**< Prediction coefficient for the energy encoding */
int nbAllocVectors; /**< Number of lines in the matrix below */
const celt_int16_t *allocVectors; /**< Number of bits in each band for several rates */
const celt_int16_t * const *bits; /**< Cache for pulses->bits mapping in each band */
/* Stuff that could go in the {en,de}coder, but we save space this way */
mdct_lookup mdct;
kiss_fftr_cfg fft;
const celt_word16_t *window;
int nbShortMdcts;
int shortMdctSize;
mdct_lookup shortMdct;
const celt_word16_t *shortWindow;
struct PsyDecay psy;
int *prob;
celt_uint32_t marker_end;
};
int check_mode(const CELTMode *mode);
#endif

178
fmod/lib/libcelt/os_support.h Executable file
View file

@ -0,0 +1,178 @@
/* Copyright (C) 2007 Jean-Marc Valin
File: os_support.h
This is the (tiny) OS abstraction layer. Aside from math.h, this is the
only place where system headers are allowed.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef OS_SUPPORT_H
#define OS_SUPPORT_H
#ifdef CUSTOM_SUPPORT
# include "custom_support.h"
#endif
#include "../../src/fmod_types.h"
#include "../../src/fmod_memory.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/** Speex wrapper for calloc. To do your own dynamic allocation, all you need to do is replace this function, celt_realloc and celt_free
NOTE: celt_alloc needs to CLEAR THE MEMORY */
#ifndef OVERRIDE_CELT_ALLOC
static FMOD_INLINE void *celt_alloc (int size)
{
/* WARNING: this is not equivalent to malloc(). If you want to use malloc()
or your own allocator, YOU NEED TO CLEAR THE MEMORY ALLOCATED. Otherwise
you will experience strange bugs */
#ifdef FMOD_CELT_ENCODER
return calloc(1, size);
#else
return FMOD_Memory_Calloc(size);
#endif
}
#endif
/** Same as celt_alloc, except that the area is only needed inside a Speex call (might cause problem with wideband though) */
#ifndef OVERRIDE_CELT_ALLOC_SCRATCH
static FMOD_INLINE void *celt_alloc_scratch (int size)
{
/* Scratch space doesn't need to be cleared */
#ifdef FMOD_CELT_ENCODER
return calloc(1, size);
#else
return FMOD_Memory_Calloc(size);
#endif
}
#endif
/** Speex wrapper for realloc. To do your own dynamic allocation, all you need to do is replace this function, celt_alloc and celt_free */
#ifndef OVERRIDE_CELT_REALLOC
static FMOD_INLINE void *celt_realloc (void *ptr, int size)
{
#ifdef FMOD_CELT_ENCODER
return realloc(ptr, size);
#else
return FMOD_Memory_ReAlloc(ptr, size);
#endif
}
#endif
/** Speex wrapper for calloc. To do your own dynamic allocation, all you need to do is replace this function, celt_realloc and celt_alloc */
#ifndef OVERRIDE_CELT_FREE
static FMOD_INLINE void celt_free (void *ptr)
{
#ifdef FMOD_CELT_ENCODER
free(ptr);
#else
FMOD_Memory_Free(ptr);
#endif
}
#endif
/** Same as celt_free, except that the area is only needed inside a Speex call (might cause problem with wideband though) */
#ifndef OVERRIDE_CELT_FREE_SCRATCH
static FMOD_INLINE void celt_free_scratch (void *ptr)
{
#ifdef FMOD_CELT_ENCODER
free(ptr);
#else
FMOD_Memory_Free(ptr);
#endif
}
#endif
/** Copy n bytes of memory from src to dst. The 0* term provides compile-time type checking */
#ifndef OVERRIDE_CELT_COPY
#define CELT_COPY(dst, src, n) (FMOD_memcpy((dst), (src), (n)*sizeof(*(dst)) + 0*((dst)-(src)) ))
#endif
/** Copy n bytes of memory from src to dst, allowing overlapping regions. The 0* term
provides compile-time type checking */
#ifndef OVERRIDE_CELT_MOVE
#define CELT_MOVE(dst, src, n) (memmove((dst), (src), (n)*sizeof(*(dst)) + 0*((dst)-(src)) ))
#endif
/** Set n bytes of memory to value of c, starting at address s */
#ifndef OVERRIDE_CELT_MEMSET
#define CELT_MEMSET(dst, c, n) (FMOD_memset((dst), (c), (n)*sizeof(*(dst))))
#endif
#ifndef OVERRIDE_CELT_FATAL
static FMOD_INLINE void _celt_fatal(const char *str, const char *file, int line)
{
fprintf (stderr, "Fatal (internal) error in %s, line %d: %s\n", file, line, str);
abort();
}
#endif
#ifndef OVERRIDE_CELT_WARNING
static FMOD_INLINE void celt_warning(const char *str)
{
#ifndef DISABLE_WARNINGS
fprintf (stderr, "warning: %s\n", str);
#endif
}
#endif
#ifndef OVERRIDE_CELT_WARNING_INT
static FMOD_INLINE void celt_warning_int(const char *str, int val)
{
#ifndef DISABLE_WARNINGS
fprintf (stderr, "warning: %s %d\n", str, val);
#endif
}
#endif
#ifndef OVERRIDE_CELT_NOTIFY
static FMOD_INLINE void celt_notify(const char *str)
{
#ifndef DISABLE_NOTIFICATIONS
fprintf (stderr, "notification: %s\n", str);
#endif
}
#endif
/*#ifdef __GNUC__
#pragma GCC poison printf sprintf
#pragma GCC poison malloc free realloc calloc
#endif*/
#endif /* OS_SUPPORT_H */

237
fmod/lib/libcelt/pitch.c Executable file
View file

@ -0,0 +1,237 @@
/* (C) 2007-2008 Jean-Marc Valin, CSIRO
*/
/**
@file pitch.c
@brief Pitch analysis
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/*#include "_kiss_fft_guts.h"
#include "kiss_fftr.h"*/
#include "kfft_single.h"
#include "pitch.h"
#include "psy.h"
#include "os_support.h"
#include "mathops.h"
#include "modes.h"
#include "stack_alloc.h"
kiss_fftr_cfg pitch_state_alloc(int max_lag)
{
return real16_fft_alloc(max_lag);
}
void pitch_state_free(kiss_fftr_cfg st)
{
real16_fft_free(st);
}
#ifdef FIXED_POINT
static void normalise16(celt_word16_t *x, int len, celt_word16_t val)
{
int i;
celt_word16_t maxabs;
maxabs = celt_maxabs16(x,len);
if (maxabs > val)
{
int shift = 0;
while (maxabs > val)
{
maxabs >>= 1;
shift++;
}
if (shift==0)
return;
i=0;
do{
x[i] = SHR16(x[i], shift);
} while (++i<len);
} else {
int shift=0;
if (maxabs == 0)
return;
val >>= 1;
while (maxabs < val)
{
val >>= 1;
shift++;
}
if (shift==0)
return;
i=0;
do{
x[i] = SHL16(x[i], shift);
} while (++i<len);
}
}
#else
#define normalise16(x,len,val)
#endif
#define INPUT_SHIFT 15
void find_spectral_pitch(const CELTMode *m, kiss_fftr_cfg fft, const struct PsyDecay *decay, const celt_sig_t * celt_restrict x, const celt_sig_t * celt_restrict y, const celt_word16_t * celt_restrict window, celt_word16_t * celt_restrict spectrum, int len, int max_pitch, int *pitch)
{
int c, i;
VARDECL(celt_word16_t, _X);
VARDECL(celt_word16_t, _Y);
const celt_word16_t * celt_restrict wptr;
#ifndef SHORTCUTS
VARDECL(celt_mask_t, curve);
#endif
celt_word16_t * celt_restrict X, * celt_restrict Y;
celt_word16_t * celt_restrict Xptr, * celt_restrict Yptr;
const celt_sig_t * celt_restrict yptr;
int n2;
int L2;
const int C = CHANNELS(m);
const int overlap = OVERLAP(m);
const int lag = MAX_PERIOD;
SAVE_STACK;
n2 = lag>>1;
L2 = len>>1;
ALLOC(_X, lag, celt_word16_t);
X = _X;
#ifndef SHORTCUTS
ALLOC(curve, n2, celt_mask_t);
#endif
CELT_MEMSET(X,0,lag);
/* Sum all channels of the current frame and copy into X in bit-reverse order */
for (c=0;c<C;c++)
{
const celt_sig_t * celt_restrict xptr = &x[c];
for (i=0;i<L2;i++)
{
X[2*BITREV(fft,i)] += SHR32(*xptr,INPUT_SHIFT);
xptr += C;
X[2*BITREV(fft,i)+1] += SHR32(*xptr,INPUT_SHIFT);
xptr += C;
}
}
/* Applying the window in the bit-reverse domain. It's a bit weird, but it
can help save memory */
wptr = window;
for (i=0;i<overlap>>1;i++)
{
X[2*BITREV(fft,i)] = MULT16_16_Q15(wptr[0], X[2*BITREV(fft,i)]);
X[2*BITREV(fft,i)+1] = MULT16_16_Q15(wptr[1], X[2*BITREV(fft,i)+1]);
X[2*BITREV(fft,L2-i-1)] = MULT16_16_Q15(wptr[1], X[2*BITREV(fft,L2-i-1)]);
X[2*BITREV(fft,L2-i-1)+1] = MULT16_16_Q15(wptr[0], X[2*BITREV(fft,L2-i-1)+1]);
wptr += 2;
}
normalise16(X, lag, 8192);
/*for (i=0;i<lag;i++) printf ("%d ", X[i]);printf ("\n");*/
/* Forward real FFT (in-place) */
real16_fft_inplace(fft, X, lag);
if (spectrum)
{
for (i=0;i<lag/4;i++)
{
spectrum[2*i] = X[4*i];
spectrum[2*i+1] = X[4*i+1];
}
}
#ifndef SHORTCUTS
compute_masking(decay, X, curve, lag);
#endif
/* Deferred allocation to reduce peak stack usage */
ALLOC(_Y, lag, celt_word16_t);
Y = _Y;
yptr = &y[0];
/* Copy first channel of the past audio into Y in bit-reverse order */
for (i=0;i<n2;i++)
{
Y[2*BITREV(fft,i)] = SHR32(*yptr,INPUT_SHIFT);
yptr += C;
Y[2*BITREV(fft,i)+1] = SHR32(*yptr,INPUT_SHIFT);
yptr += C;
}
/* Add remaining channels into Y in bit-reverse order */
for (c=1;c<C;c++)
{
yptr = &y[c];
for (i=0;i<n2;i++)
{
Y[2*BITREV(fft,i)] += SHR32(*yptr,INPUT_SHIFT);
yptr += C;
Y[2*BITREV(fft,i)+1] += SHR32(*yptr,INPUT_SHIFT);
yptr += C;
}
}
normalise16(Y, lag, 8192);
/* Forward real FFT (in-place) */
real16_fft_inplace(fft, Y, lag);
/* Compute cross-spectrum using the inverse masking curve as weighting */
Xptr = &X[2];
Yptr = &Y[2];
for (i=1;i<n2;i++)
{
celt_word16_t Xr, Xi, n;
/* weight = 1/sqrt(curve) */
Xr = Xptr[0];
Xi = Xptr[1];
#ifdef SHORTCUTS
/*n = SHR32(32767,(celt_ilog2(EPSILON+curve[i])>>1));*/
n = 1+(8192>>(celt_ilog2(1+MULT16_16(Xr,Xr)+MULT16_16(Xi,Xi))>>1));
/* Pre-multiply X by n, so we can keep everything in 16 bits */
Xr = MULT16_16_16(n, Xr);
Xi = MULT16_16_16(n, Xi);
#else
n = celt_rsqrt(EPSILON+curve[i]);
/* Pre-multiply X by n, so we can keep everything in 16 bits */
Xr = EXTRACT16(SHR32(MULT16_16(n, Xr),3));
Xi = EXTRACT16(SHR32(MULT16_16(n, Xi),3));
#endif
/* Cross-spectrum between X and conj(Y) */
*Xptr++ = ADD16(MULT16_16_Q15(Xr, Yptr[0]), MULT16_16_Q15(Xi,Yptr[1]));
*Xptr++ = SUB16(MULT16_16_Q15(Xr, Yptr[1]), MULT16_16_Q15(Xi,Yptr[0]));
Yptr += 2;
}
/*printf ("\n");*/
X[0] = X[1] = 0;
/*for (i=0;i<lag;i++) printf ("%d ", X[i]);printf ("\n");*/
normalise16(X, lag, 50);
/* Inverse half-complex to real FFT gives us the correlation */
real16_ifft(fft, X, Y, lag);
/* The peak in the correlation gives us the pitch */
*pitch = find_max16(Y, max_pitch);
RESTORE_STACK;
}

53
fmod/lib/libcelt/pitch.h Executable file
View file

@ -0,0 +1,53 @@
/* (C) 2007-2008 Jean-Marc Valin, CSIRO
*/
/**
@file pitch.h
@brief Pitch analysis
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _PITCH_H
#define _PITCH_H
#include "kiss_fftr.h"
#include "psy.h"
#include "modes.h"
kiss_fftr_cfg pitch_state_alloc(int max_lag);
void pitch_state_free(kiss_fftr_cfg st);
/** Find the optimal delay for the pitch prediction. Computation is
done in the frequency domain, both to save time and to make it
easier to apply psychoacoustic weighting */
void find_spectral_pitch(const CELTMode *m, kiss_fftr_cfg fft, const struct PsyDecay *decay, const celt_sig_t * celt_restrict x, const celt_sig_t * celt_restrict y, const celt_word16_t * celt_restrict window, celt_word16_t * celt_restrict X, int len, int max_pitch, int *pitch);
#endif

212
fmod/lib/libcelt/psy.c Executable file
View file

@ -0,0 +1,212 @@
/* (C) 2007 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "psy.h"
#include <math.h>
#include "os_support.h"
#include "arch.h"
#include "stack_alloc.h"
#include "mathops.h"
/* The Vorbis freq<->Bark mapping */
#define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
#define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
#ifndef STATIC_MODES
/* Psychoacoustic spreading function. The idea here is compute a first order
recursive filter. The filter coefficient is frequency dependent and
chosen such that we have a -10dB/Bark slope on the right side and a -25dB/Bark
slope on the left side. */
void psydecay_init(struct PsyDecay *decay, int len, celt_int32_t Fs)
{
int i;
celt_word16_t *decayR = (celt_word16_t*)celt_alloc(sizeof(celt_word16_t)*len);
decay->decayR = decayR;
if (decayR==NULL)
return;
for (i=0;i<len;i++)
{
float f;
float deriv;
/* Real frequency (in Hz) */
f = Fs*i*(1/(2.f*len));
/* This is the derivative of the Vorbis freq->Bark function (see above) */
deriv = (8.288e-8 * f)/(3.4225e-16 *f*f*f*f + 1) + .009694/(5.476e-7 *f*f + 1) + 1e-4;
/* Back to FFT bin units */
deriv *= Fs*(1/(2.f*len));
/* decay corresponding to -10dB/Bark */
decayR[i] = Q15ONE*pow(.1f, deriv);
/* decay corresponding to -25dB/Bark */
/*decay->decayL[i] = Q15ONE*pow(0.0031623f, deriv);*/
/*printf ("%f %f\n", decayL[i], decayR[i]);*/
}
}
void psydecay_clear(struct PsyDecay *decay)
{
celt_free((celt_word16_t *)decay->decayR);
/*celt_free(decay->decayL);*/
}
#endif
static void spreading_func(const struct PsyDecay *d, celt_word32_t * celt_restrict psd, int len)
{
int i;
celt_word32_t mem;
/* Compute right slope (-10 dB/Bark) */
mem=psd[0];
for (i=0;i<len;i++)
{
/* psd = (1-decay)*psd + decay*mem */
psd[i] = EPSILON + psd[i] + MULT16_32_Q15(d->decayR[i],mem-psd[i]);
mem = psd[i];
}
/* Compute left slope (-25 dB/Bark) */
mem=psd[len-1];
for (i=len-1;i>=0;i--)
{
/* Left side has around twice the slope as the right side, so we just
square the coef instead of storing two sets of decay coefs */
celt_word16_t decayL = MULT16_16_Q15(d->decayR[i], d->decayR[i]);
/* psd = (1-decay)*psd + decay*mem */
psd[i] = EPSILON + psd[i] + MULT16_32_Q15(decayL,mem-psd[i]);
mem = psd[i];
}
#if 0 /* Prints signal and mask energy per critical band */
for (i=0;i<25;i++)
{
int start,end;
int j;
celt_word32_t Esig=0, Emask=0;
start = (int)floor(fromBARK((float)i)*(2*len)/Fs);
if (start<0)
start = 0;
end = (int)ceil(fromBARK((float)(i+1))*(2*len)/Fs);
if (end<=start)
end = start+1;
if (end>len-1)
end = len-1;
for (j=start;j<end;j++)
{
Esig += psd[j];
Emask += mask[j];
}
printf ("%f %f ", Esig, Emask);
}
printf ("\n");
#endif
}
/* Compute a marking threshold from the spectrum X. */
void compute_masking(const struct PsyDecay *decay, celt_word16_t *X, celt_mask_t * celt_restrict mask, int len)
{
int i;
int N;
N=len>>1;
mask[0] = MULT16_16(X[0], X[0]);
for (i=1;i<N;i++)
mask[i] = ADD32(MULT16_16(X[i*2], X[i*2]), MULT16_16(X[i*2+1], X[i*2+1]));
/* TODO: Do tone masking */
/* Noise masking */
spreading_func(decay, mask, N);
}
#ifdef EXP_PSY /* Not needed for now, but will be useful in the future */
void compute_mdct_masking(const struct PsyDecay *decay, celt_word32_t *X, celt_word16_t *tonality, celt_word16_t *long_window, celt_mask_t *mask, int len)
{
int i;
VARDECL(float, psd);
SAVE_STACK;
ALLOC(psd, len, float);
for (i=0;i<len;i++)
psd[i] = X[i]*X[i]*tonality[i];
for (i=1;i<len-1;i++)
mask[i] = .5*psd[i] + .25*(psd[i-1]+psd[i+1]);
/*psd[0] = .5*mask[0]+.25*(mask[1]+mask[2]);*/
mask[0] = .5*psd[0]+.5*psd[1];
mask[len-1] = .5*(psd[len-1]+psd[len-2]);
/* TODO: Do tone masking */
/* Noise masking */
spreading_func(decay, mask, len);
RESTORE_STACK;
}
void compute_tonality(const CELTMode *m, celt_word16_t * celt_restrict X, celt_word16_t * mem, int len, celt_word16_t *tonality, int mdct_size)
{
int i;
celt_word16_t norm_1;
celt_word16_t *mem2;
int N = len>>2;
mem2 = mem+2*N;
X[0] = 0;
X[1] = 0;
tonality[0] = 1;
for (i=1;i<N;i++)
{
celt_word16_t re, im, re2, im2;
re = X[2*i];
im = X[2*i+1];
/* Normalise spectrum */
norm_1 = celt_rsqrt(.01+MAC16_16(MULT16_16(re,re), im,im));
re = MULT16_16(re, norm_1);
im = MULT16_16(im, norm_1);
/* Phase derivative */
re2 = re*mem[2*i] + im*mem[2*i+1];
im2 = im*mem[2*i] - re*mem[2*i+1];
mem[2*i] = re;
mem[2*i+1] = im;
/* Phase second derivative */
re = re2*mem2[2*i] + im2*mem2[2*i+1];
im = im2*mem2[2*i] - re2*mem2[2*i+1];
mem2[2*i] = re2;
mem2[2*i+1] = im2;
/*printf ("%f ", re);*/
X[2*i] = re;
X[2*i+1] = im;
}
/*printf ("\n");*/
for (i=0;i<mdct_size;i++)
{
tonality[i] = 1.0-X[2*i]*X[2*i]*X[2*i];
if (tonality[i]>1)
tonality[i] = 1;
if (tonality[i]<.02)
tonality[i]=.02;
}
}
#endif

56
fmod/lib/libcelt/psy.h Executable file
View file

@ -0,0 +1,56 @@
/* (C) 2007 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PSY_H
#define PSY_H
#include "arch.h"
#include "celt.h"
struct PsyDecay {
/*celt_word16_t *decayL;*/
const celt_word16_t * celt_restrict decayR;
};
/** Pre-compute the decay of the psycho-acoustic spreading function */
void psydecay_init(struct PsyDecay *decay, int len, celt_int32_t Fs);
/** Free the memory allocated for the spreading function */
void psydecay_clear(struct PsyDecay *decay);
/** Compute the masking curve for an input (DFT) spectrum X */
void compute_masking(const struct PsyDecay *decay, celt_word16_t *X, celt_mask_t * celt_restrict mask, int len);
/** Compute the masking curve for an input (MDCT) spectrum X */
void compute_mdct_masking(const struct PsyDecay *decay, celt_word32_t *X, celt_word16_t *tonality, celt_word16_t *long_window, celt_mask_t *mask, int len);
void compute_tonality(const CELTMode *m, celt_word16_t * celt_restrict X, celt_word16_t * mem, int len, celt_word16_t *tonality, int mdct_size);
#endif /* PSY_H */

325
fmod/lib/libcelt/quant_bands.c Executable file
View file

@ -0,0 +1,325 @@
/* (C) 2007-2008 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "quant_bands.h"
#include "laplace.h"
#include <math.h>
#include "os_support.h"
#include "arch.h"
#include "mathops.h"
#include "stack_alloc.h"
#ifdef FIXED_POINT
const celt_word16_t eMeans[24] = {1920, -341, -512, -107, 43, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
#else
const celt_word16_t eMeans[24] = {7.5f, -1.33f, -2.f, -0.42f, 0.17f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
#endif
int intra_decision(celt_word16_t *eBands, celt_word16_t *oldEBands, int len)
{
int i;
celt_word32_t dist = 0;
for (i=0;i<len;i++)
{
celt_word16_t d = SUB16(eBands[i], oldEBands[i]);
dist = MAC16_16(dist, d,d);
}
return SHR32(dist,16) > 2*len;
}
int *quant_prob_alloc(const CELTMode *m)
{
int i;
int *prob;
prob = celt_alloc(4*m->nbEBands*sizeof(int));
if (prob==NULL)
return NULL;
for (i=0;i<m->nbEBands;i++)
{
prob[2*i] = 6000-i*200;
prob[2*i+1] = ec_laplace_get_start_freq(prob[2*i]);
}
for (i=0;i<m->nbEBands;i++)
{
prob[2*m->nbEBands+2*i] = 9000-i*240;
prob[2*m->nbEBands+2*i+1] = ec_laplace_get_start_freq(prob[2*m->nbEBands+2*i]);
}
return prob;
}
void quant_prob_free(int *freq)
{
celt_free(freq);
}
#ifdef FMOD_CELT_ENCODER
unsigned quant_coarse_energy(const CELTMode *m, celt_word16_t *eBands, celt_word16_t *oldEBands, int budget, int intra, int *prob, celt_word16_t *error, ec_enc *enc)
{
int i, c;
unsigned bits;
unsigned bits_used = 0;
celt_word16_t prev[2] = {0,0};
celt_word16_t coef = m->ePredCoef;
celt_word16_t beta;
const int C = CHANNELS(m);
if (intra)
{
coef = 0;
prob += 2*m->nbEBands;
}
/* The .8 is a heuristic */
beta = MULT16_16_Q15(QCONST16(.8f,15),coef);
bits = ec_enc_tell(enc, 0);
/* Encode at a fixed coarse resolution */
for (i=0;i<m->nbEBands;i++)
{
c=0;
do {
int qi;
celt_word16_t q; /* dB */
celt_word16_t x; /* dB */
celt_word16_t f; /* Q8 */
celt_word16_t mean = MULT16_16_Q15(Q15ONE-coef,eMeans[i]);
x = eBands[i+c*m->nbEBands];
#ifdef FIXED_POINT
f = x-mean -MULT16_16_Q15(coef,oldEBands[i+c*m->nbEBands])-prev[c];
/* Rounding to nearest integer here is really important! */
qi = (f+128)>>8;
#else
f = x-mean-coef*oldEBands[i+c*m->nbEBands]-prev[c];
/* Rounding to nearest integer here is really important! */
qi = (int)floor(.5f+f);
#endif
/* If we don't have enough bits to encode all the energy, just assume something safe.
We allow slightly busting the budget here */
bits_used=ec_enc_tell(enc, 0) - bits;
if (bits_used > budget)
{
qi = -1;
error[i+c*m->nbEBands] = 128;
} else {
ec_laplace_encode_start(enc, &qi, prob[2*i], prob[2*i+1]);
error[i+c*m->nbEBands] = f - SHL16(qi,8);
}
q = qi*DB_SCALING;
oldEBands[i+c*m->nbEBands] = MULT16_16_Q15(coef,oldEBands[i+c*m->nbEBands])+(mean+prev[c]+q);
prev[c] = mean+prev[c]+MULT16_16_Q15(Q15ONE-beta,q);
} while (++c < C);
}
return bits_used;
}
void quant_fine_energy(const CELTMode *m, celt_ener_t *eBands, celt_word16_t *oldEBands, celt_word16_t *error, int *fine_quant, ec_enc *enc)
{
int i, c;
const int C = CHANNELS(m);
/* Encode finer resolution */
for (i=0;i<m->nbEBands;i++)
{
celt_int16_t frac = 1<<fine_quant[i];
if (fine_quant[i] <= 0)
continue;
c=0;
do {
int q2;
celt_word16_t offset;
#ifdef FIXED_POINT
/* Has to be without rounding */
q2 = (error[i+c*m->nbEBands]+QCONST16(.5f,8))>>(8-fine_quant[i]);
#else
q2 = (int)floor((error[i+c*m->nbEBands]+.5f)*frac);
#endif
if (q2 > frac-1)
q2 = frac-1;
ec_enc_bits(enc, q2, fine_quant[i]);
#ifdef FIXED_POINT
offset = SUB16(SHR16(SHL16(q2,8)+QCONST16(.5,8),fine_quant[i]),QCONST16(.5f,8));
#else
offset = (q2+.5f)*(1<<(14-fine_quant[i]))*(1.f/16384) - .5f;
#endif
oldEBands[i+c*m->nbEBands] += offset;
error[i+c*m->nbEBands] -= offset;
eBands[i+c*m->nbEBands] = log2Amp(oldEBands[i+c*m->nbEBands]);
/*printf ("%f ", error[i] - offset);*/
} while (++c < C);
}
for (i=0;i<C*m->nbEBands;i++)
eBands[i] = log2Amp(oldEBands[i]);
}
void quant_energy_finalise(const CELTMode *m, celt_ener_t *eBands, celt_word16_t *oldEBands, celt_word16_t *error, int *fine_quant, int *fine_priority, int bits_left, ec_enc *enc)
{
int i, prio, c;
const int C = CHANNELS(m);
/* Use up the remaining bits */
for (prio=0;prio<2;prio++)
{
for (i=0;i<m->nbEBands && bits_left>=C ;i++)
{
if (fine_quant[i] >= 7 || fine_priority[i]!=prio)
continue;
c=0;
do {
int q2;
celt_word16_t offset;
q2 = error[i+c*m->nbEBands]<0 ? 0 : 1;
ec_enc_bits(enc, q2, 1);
#ifdef FIXED_POINT
offset = SHR16(SHL16(q2,8)-QCONST16(.5,8),fine_quant[i]+1);
#else
offset = (q2-.5f)*(1<<(14-fine_quant[i]-1))*(1.f/16384);
#endif
oldEBands[i+c*m->nbEBands] += offset;
bits_left--;
} while (++c < C);
}
}
for (i=0;i<C*m->nbEBands;i++)
{
eBands[i] = log2Amp(oldEBands[i]);
if (oldEBands[i] < -QCONST16(7.f,8))
oldEBands[i] = -QCONST16(7.f,8);
}
}
#endif
void unquant_coarse_energy(const CELTMode *m, celt_ener_t *eBands, celt_word16_t *oldEBands, int budget, int intra, int *prob, ec_dec *dec)
{
int i, c;
unsigned bits;
celt_word16_t prev[2] = {0, 0};
celt_word16_t coef = m->ePredCoef;
celt_word16_t beta;
const int C = CHANNELS(m);
if (intra)
{
coef = 0;
prob += 2*m->nbEBands;
}
/* The .8 is a heuristic */
beta = MULT16_16_Q15(QCONST16(.8f,15),coef);
bits = ec_dec_tell(dec, 0);
/* Decode at a fixed coarse resolution */
for (i=0;i<m->nbEBands;i++)
{
c=0;
do {
int qi;
celt_word16_t q;
celt_word16_t mean = MULT16_16_Q15(Q15ONE-coef,eMeans[i]);
/* If we didn't have enough bits to encode all the energy, just assume something safe.
We allow slightly busting the budget here */
if (ec_dec_tell(dec, 0) - bits > budget)
qi = -1;
else
qi = ec_laplace_decode_start(dec, prob[2*i], prob[2*i+1]);
q = qi*DB_SCALING;
oldEBands[i+c*m->nbEBands] = MULT16_16_Q15(coef,oldEBands[i+c*m->nbEBands])+(mean+prev[c]+q);
prev[c] = mean+prev[c]+MULT16_16_Q15(Q15ONE-beta,q);
} while (++c < C);
}
}
void unquant_fine_energy(const CELTMode *m, celt_ener_t *eBands, celt_word16_t *oldEBands, int *fine_quant, ec_dec *dec)
{
int i, c;
const int C = CHANNELS(m);
/* Decode finer resolution */
for (i=0;i<m->nbEBands;i++)
{
if (fine_quant[i] <= 0)
continue;
c=0;
do {
int q2;
celt_word16_t offset;
q2 = ec_dec_bits(dec, fine_quant[i]);
#ifdef FIXED_POINT
offset = SUB16(SHR16(SHL16(q2,8)+QCONST16(.5,8),fine_quant[i]),QCONST16(.5f,8));
#else
offset = (q2+.5f)*(1<<(14-fine_quant[i]))*(1.f/16384) - .5f;
#endif
oldEBands[i+c*m->nbEBands] += offset;
} while (++c < C);
}
for (i=0;i<C*m->nbEBands;i++)
eBands[i] = log2Amp(oldEBands[i]);
}
void unquant_energy_finalise(const CELTMode *m, celt_ener_t *eBands, celt_word16_t *oldEBands, int *fine_quant, int *fine_priority, int bits_left, ec_dec *dec)
{
int i, prio, c;
const int C = CHANNELS(m);
/* Use up the remaining bits */
for (prio=0;prio<2;prio++)
{
for (i=0;i<m->nbEBands && bits_left>=C ;i++)
{
if (fine_quant[i] >= 7 || fine_priority[i]!=prio)
continue;
c=0;
do {
int q2;
celt_word16_t offset;
q2 = ec_dec_bits(dec, 1);
#ifdef FIXED_POINT
offset = SHR16(SHL16(q2,8)-QCONST16(.5,8),fine_quant[i]+1);
#else
offset = (q2-.5f)*(1<<(14-fine_quant[i]-1))*(1.f/16384);
#endif
oldEBands[i+c*m->nbEBands] += offset;
bits_left--;
} while (++c < C);
}
}
for (i=0;i<C*m->nbEBands;i++)
{
eBands[i] = log2Amp(oldEBands[i]);
if (oldEBands[i] < -QCONST16(7.f,8))
oldEBands[i] = -QCONST16(7.f,8);
}
}

70
fmod/lib/libcelt/quant_bands.h Executable file
View file

@ -0,0 +1,70 @@
/* (C) 2007 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef QUANT_BANDS
#define QUANT_BANDS
#include "arch.h"
#include "modes.h"
#include "entenc.h"
#include "entdec.h"
#include "mathops.h"
static FMOD_INLINE celt_word16_t amp2Log(celt_word32_t amp)
{
return celt_log2(MAX32(QCONST32(.001f,14),SHL32(amp,2)));
}
static FMOD_INLINE celt_word32_t log2Amp(celt_word16_t lg)
{
return PSHR32(celt_exp2(SHL16(lg,3)),4);
}
int *quant_prob_alloc(const CELTMode *m);
void quant_prob_free(int *freq);
void compute_fine_allocation(const CELTMode *m, int *bits, int budget);
int intra_decision(celt_word16_t *eBands, celt_word16_t *oldEBands, int len);
unsigned quant_coarse_energy(const CELTMode *m, celt_word16_t *eBands, celt_word16_t *oldEBands, int budget, int intra, int *prob, celt_word16_t *error, ec_enc *enc);
void quant_fine_energy(const CELTMode *m, celt_ener_t *eBands, celt_word16_t *oldEBands, celt_word16_t *error, int *fine_quant, ec_enc *enc);
void quant_energy_finalise(const CELTMode *m, celt_ener_t *eBands, celt_word16_t *oldEBands, celt_word16_t *error, int *fine_quant, int *fine_priority, int bits_left, ec_enc *enc);
void unquant_coarse_energy(const CELTMode *m, celt_ener_t *eBands, celt_word16_t *oldEBands, int budget, int intra, int *prob, ec_dec *dec);
void unquant_fine_energy(const CELTMode *m, celt_ener_t *eBands, celt_word16_t *oldEBands, int *fine_quant, ec_dec *dec);
void unquant_energy_finalise(const CELTMode *m, celt_ener_t *eBands, celt_word16_t *oldEBands, int *fine_quant, int *fine_priority, int bits_left, ec_dec *dec);
#endif /* QUANT_BANDS */

226
fmod/lib/libcelt/rangedec.c Executable file
View file

@ -0,0 +1,226 @@
/* (C) 2001-2008 Timothy B. Terriberry
(C) 2008 Jean-Marc Valin */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "arch.h"
#include "entdec.h"
#include "mfrngcod.h"
/*A range decoder.
This is an entropy decoder based upon \cite{Mar79}, which is itself a
rediscovery of the FIFO arithmetic code introduced by \cite{Pas76}.
It is very similar to arithmetic encoding, except that encoding is done with
digits in any base, instead of with bits, and so it is faster when using
larger bases (i.e.: a byte).
The author claims an average waste of $\frac{1}{2}\log_b(2b)$ bits, where $b$
is the base, longer than the theoretical optimum, but to my knowledge there
is no published justification for this claim.
This only seems true when using near-infinite precision arithmetic so that
the process is carried out with no rounding errors.
IBM (the author's employer) never sought to patent the idea, and to my
knowledge the algorithm is unencumbered by any patents, though its
performance is very competitive with proprietary arithmetic coding.
The two are based on very similar ideas, however.
An excellent description of implementation details is available at
http://www.arturocampos.com/ac_range.html
A recent work \cite{MNW98} which proposes several changes to arithmetic
encoding for efficiency actually re-discovers many of the principles
behind range encoding, and presents a good theoretical analysis of them.
@PHDTHESIS{Pas76,
author="Richard Clark Pasco",
title="Source coding algorithms for fast data compression",
school="Dept. of Electrical Engineering, Stanford University",
address="Stanford, CA",
month=May,
year=1976
}
@INPROCEEDINGS{Mar79,
author="Martin, G.N.N.",
title="Range encoding: an algorithm for removing redundancy from a digitised
message",
booktitle="Video & Data Recording Conference",
year=1979,
address="Southampton",
month=Jul
}
@ARTICLE{MNW98,
author="Alistair Moffat and Radford Neal and Ian H. Witten",
title="Arithmetic Coding Revisited",
journal="{ACM} Transactions on Information Systems",
year=1998,
volume=16,
number=3,
pages="256--294",
month=Jul,
URL="http://www.stanford.edu/class/ee398/handouts/papers/Moffat98ArithmCoding.pdf"
}*/
/*Gets the next byte of input.
After all the bytes in the current packet have been consumed, and the extra
end code returned if needed, this function will continue to return zero each
time it is called.
Return: The next byte of input.*/
static int ec_dec_in(ec_dec *_this){
int ret;
ret=ec_byte_read1(_this->buf);
if(ret<0){
ret=0;
/*Needed to keep oc_dec_tell() operating correctly.*/
ec_byte_adv1(_this->buf);
}
return ret;
}
/*Normalizes the contents of dif and rng so that rng lies entirely in the
high-order symbol.*/
static FMOD_INLINE void ec_dec_normalize(ec_dec *_this){
/*If the range is too small, rescale it and input some bits.*/
while(_this->rng<=EC_CODE_BOT){
int sym;
_this->rng<<=EC_SYM_BITS;
/*Use up the remaining bits from our last symbol.*/
sym=_this->rem<<EC_CODE_EXTRA&EC_SYM_MAX;
/*Read the next value from the input.*/
_this->rem=ec_dec_in(_this);
/*Take the rest of the bits we need from this new symbol.*/
sym|=_this->rem>>EC_SYM_BITS-EC_CODE_EXTRA;
_this->dif=(_this->dif<<EC_SYM_BITS)-sym&EC_CODE_MASK;
/*dif can never be larger than EC_CODE_TOP.
This is equivalent to the slightly more readable:
if(_this->dif>EC_CODE_TOP)_this->dif-=EC_CODE_TOP;*/
_this->dif^=_this->dif&_this->dif-1&EC_CODE_TOP;
}
}
void ec_dec_init(ec_dec *_this,ec_byte_buffer *_buf){
_this->buf=_buf;
_this->rem=ec_dec_in(_this);
_this->rng=1U<<EC_CODE_EXTRA;
_this->dif=_this->rng-(_this->rem>>EC_SYM_BITS-EC_CODE_EXTRA);
/*Normalize the interval.*/
ec_dec_normalize(_this);
}
unsigned ec_decode(ec_dec *_this,unsigned _ft){
unsigned s;
_this->nrm=_this->rng/_ft;
s=(unsigned)((_this->dif-1)/_this->nrm);
return _ft-EC_MINI(s+1,_ft);
}
unsigned ec_decode_bin(ec_dec *_this,unsigned bits){
unsigned s;
ec_uint32 ft;
ft = (ec_uint32)1<<bits;
_this->nrm=_this->rng>>bits;
s=(unsigned)((_this->dif-1)/_this->nrm);
return ft-EC_MINI(s+1,ft);
}
void ec_dec_update(ec_dec *_this,unsigned _fl,unsigned _fh,unsigned _ft){
ec_uint32 s;
s=IMUL32(_this->nrm,(_ft-_fh));
_this->dif-=s;
_this->rng=_fl>0?IMUL32(_this->nrm,(_fh-_fl)):_this->rng-s;
ec_dec_normalize(_this);
}
long ec_dec_tell(ec_dec *_this,int _b){
ec_uint32 r;
int l;
long nbits;
nbits=(ec_byte_bytes(_this->buf)-(EC_CODE_BITS+EC_SYM_BITS-1)/EC_SYM_BITS)*
EC_SYM_BITS;
/*To handle the non-integral number of bits still left in the encoder state,
we compute the number of bits of low that must be encoded to ensure that
the value is inside the range for any possible subsequent bits.
Note that this is subtly different than the actual value we would end the
stream with, which tries to make as many of the trailing bits zeros as
possible.*/
nbits+=EC_CODE_BITS;
nbits<<=_b;
l=EC_ILOG(_this->rng);
r=_this->rng>>l-16;
while(_b-->0){
int b;
r=r*r>>15;
b=(int)(r>>16);
l=l<<1|b;
r>>=b;
}
return nbits-l;
}
#if 0
int ec_dec_done(ec_dec *_this){
unsigned low;
int ret;
/*Check to make sure we've used all the input bytes.
This ensures that no more ones would ever be inserted into the decoder.*/
if(_this->buf->ptr-ec_byte_get_buffer(_this->buf)<=
ec_byte_bytes(_this->buf)){
return 0;
}
/*We compute the smallest finitely odd fraction that fits inside the current
range, and write that to the stream.
This is guaranteed to yield the smallest possible encoding.*/
/*TODO: Fix this line, as it is wrong.
It doesn't seem worth being able to make this check to do an extra
subtraction for every symbol decoded.*/
low=/*What we want: _this->top-_this->rng; What we have:*/_this->dif
if(low){
unsigned end;
end=EC_CODE_TOP;
/*Ensure that the next free end is in the range.*/
if(end-low>=_this->rng){
unsigned msk;
msk=EC_CODE_TOP-1;
do{
msk>>=1;
end=(low+msk)&~msk|msk+1;
}
while(end-low>=_this->rng);
}
/*The remaining input should have been the next free end.*/
return end-low!=_this->dif;
}
return 1;
}
#endif

196
fmod/lib/libcelt/rangeenc.c Executable file
View file

@ -0,0 +1,196 @@
/* (C) 2001-2008 Timothy B. Terriberry
(C) 2008 Jean-Marc Valin */
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef FMOD_CELT_ENCODER
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "arch.h"
#include "entenc.h"
#include "mfrngcod.h"
/*A range encoder.
See rangedec.c and the references for implementation details
\cite{Mar79,MNW98}.
@INPROCEEDINGS{Mar79,
author="Martin, G.N.N.",
title="Range encoding: an algorithm for removing redundancy from a digitised
message",
booktitle="Video \& Data Recording Conference",
year=1979,
address="Southampton",
month=Jul
}
@ARTICLE{MNW98,
author="Alistair Moffat and Radford Neal and Ian H. Witten",
title="Arithmetic Coding Revisited",
journal="{ACM} Transactions on Information Systems",
year=1998,
volume=16,
number=3,
pages="256--294",
month=Jul,
URL="http://www.stanford.edu/class/ee398/handouts/papers/Moffat98ArithmCoding.pdf"
}*/
/*Outputs a symbol, with a carry bit.
If there is a potential to propagate a carry over several symbols, they are
buffered until it can be determined whether or not an actual carry will
occur.
If the counter for the buffered symbols overflows, then the stream becomes
undecodable.
This gives a theoretical limit of a few billion symbols in a single packet on
32-bit systems.
The alternative is to truncate the range in order to force a carry, but
requires similar carry tracking in the decoder, needlessly slowing it down.*/
static void ec_enc_carry_out(ec_enc *_this,int _c){
if(_c!=EC_SYM_MAX){
/*No further carry propagation possible, flush buffer.*/
int carry;
carry=_c>>EC_SYM_BITS;
/*Don't output a byte on the first write.
This compare should be taken care of by branch-prediction thereafter.*/
if(_this->rem>=0)ec_byte_write1(_this->buf,_this->rem+carry);
if(_this->ext>0){
unsigned sym;
sym=EC_SYM_MAX+carry&EC_SYM_MAX;
do ec_byte_write1(_this->buf,sym);
while(--(_this->ext)>0);
}
_this->rem=_c&EC_SYM_MAX;
}
else _this->ext++;
}
static FMOD_INLINE void ec_enc_normalize(ec_enc *_this){
/*If the range is too small, output some bits and rescale it.*/
while(_this->rng<=EC_CODE_BOT){
ec_enc_carry_out(_this,(int)(_this->low>>EC_CODE_SHIFT));
/*Move the next-to-high-order symbol into the high-order position.*/
_this->low=_this->low<<EC_SYM_BITS&EC_CODE_TOP-1;
_this->rng<<=EC_SYM_BITS;
}
}
void ec_enc_init(ec_enc *_this,ec_byte_buffer *_buf){
_this->buf=_buf;
_this->rem=-1;
_this->ext=0;
_this->low=0;
_this->rng=EC_CODE_TOP;
}
void ec_encode(ec_enc *_this,unsigned _fl,unsigned _fh,unsigned _ft){
ec_uint32 r;
r=_this->rng/_ft;
if(_fl>0){
_this->low+=_this->rng-IMUL32(r,(_ft-_fl));
_this->rng=IMUL32(r,(_fh-_fl));
}
else _this->rng-=IMUL32(r,(_ft-_fh));
ec_enc_normalize(_this);
}
void ec_encode_bin(ec_enc *_this,unsigned _fl,unsigned _fh,unsigned bits){
ec_uint32 r, ft;
r=_this->rng>>bits;
ft = (ec_uint32)1<<bits;
if(_fl>0){
_this->low+=_this->rng-IMUL32(r,(ft-_fl));
_this->rng=IMUL32(r,(_fh-_fl));
}
else _this->rng-=IMUL32(r,(ft-_fh));
ec_enc_normalize(_this);
}
long ec_enc_tell(ec_enc *_this,int _b){
ec_uint32 r;
int l;
long nbits;
nbits=(ec_byte_bytes(_this->buf)+(_this->rem>=0)+_this->ext)*EC_SYM_BITS;
/*To handle the non-integral number of bits still left in the encoder state,
we compute the number of bits of low that must be encoded to ensure that
the value is inside the range for any possible subsequent bits.
Note that this is subtly different than the actual value we would end the
stream with, which tries to make as many of the trailing bits zeros as
possible.*/
nbits+=EC_CODE_BITS;
nbits<<=_b;
l=EC_ILOG(_this->rng);
r=_this->rng>>l-16;
while(_b-->0){
int b;
r=r*r>>15;
b=(int)(r>>16);
l=l<<1|b;
r>>=b;
}
return nbits-l;
}
void ec_enc_done(ec_enc *_this){
/*We compute the integer in the current interval that has the largest number
of trailing zeros, and write that to the stream.
This is guaranteed to yield the smallest possible encoding.*/
if(_this->low){
ec_uint32 end;
end=EC_CODE_TOP;
/*Ensure that the end value is in the range.*/
if(end-_this->low>=_this->rng){
ec_uint32 msk;
msk=EC_CODE_TOP-1;
do{
msk>>=1;
end=_this->low+msk&~msk|msk+1;
}
while(end-_this->low>=_this->rng);
}
/*The remaining output is the next free end.*/
while(end){
ec_enc_carry_out(_this,end>>EC_CODE_SHIFT);
end=end<<EC_SYM_BITS&EC_CODE_TOP-1;
}
}
/*If we have a buffered byte flush it into the output buffer.*/
if(_this->rem>0||_this->ext>0){
ec_enc_carry_out(_this,0);
_this->rem=-1;
}
}
#endif /* FMOD_CELT_ENCODER */

212
fmod/lib/libcelt/rate.c Executable file
View file

@ -0,0 +1,212 @@
/* (C) 2007-2009 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <math.h>
#include "modes.h"
#include "cwrs.h"
#include "arch.h"
#include "os_support.h"
#include "entcode.h"
#include "rate.h"
#ifndef STATIC_MODES
celt_int16_t **compute_alloc_cache(CELTMode *m, int C)
{
int i, prevN;
int error = 0;
celt_int16_t **bits;
const celt_int16_t *eBands = m->eBands;
bits = celt_alloc(m->nbEBands*sizeof(celt_int16_t*));
if (bits==NULL)
return NULL;
prevN = -1;
for (i=0;i<m->nbEBands;i++)
{
int N = C*(eBands[i+1]-eBands[i]);
if (N == prevN && eBands[i] < m->pitchEnd)
{
bits[i] = bits[i-1];
} else {
bits[i] = celt_alloc(MAX_PULSES*sizeof(celt_int16_t));
if (bits[i]!=NULL) {
get_required_bits(bits[i], N, MAX_PULSES, BITRES);
} else {
error=1;
}
prevN = N;
}
}
if (error)
{
const celt_int16_t *prevPtr = NULL;
if (bits!=NULL)
{
for (i=0;i<m->nbEBands;i++)
{
if (bits[i] != prevPtr)
{
prevPtr = bits[i];
celt_free((int*)bits[i]);
}
}
free(bits);
bits=NULL;
}
}
return bits;
}
#endif /* !STATIC_MODES */
static void interp_bits2pulses(const CELTMode *m, int *bits1, int *bits2, int total, int *bits, int *ebits, int *fine_priority, int len)
{
int psum;
int lo, hi;
int j;
const int C = CHANNELS(m);
SAVE_STACK;
lo = 0;
hi = 1<<BITRES;
while (hi-lo != 1)
{
int mid = (lo+hi)>>1;
psum = 0;
for (j=0;j<len;j++)
psum += ((1<<BITRES)-mid)*bits1[j] + mid*bits2[j];
if (psum > (total<<BITRES))
hi = mid;
else
lo = mid;
}
psum = 0;
/*printf ("interp bisection gave %d\n", lo);*/
for (j=0;j<len;j++)
{
bits[j] = ((1<<BITRES)-lo)*bits1[j] + lo*bits2[j];
psum += bits[j];
}
/* Allocate the remaining bits */
{
int left, perband;
left = (total<<BITRES)-psum;
perband = left/len;
for (j=0;j<len;j++)
bits[j] += perband;
left = left-len*perband;
for (j=0;j<left;j++)
bits[j]++;
}
for (j=0;j<len;j++)
{
int N, d;
int offset;
N=m->eBands[j+1]-m->eBands[j];
d=C*N<<BITRES;
offset = 50 - log2_frac(N, 4);
/* Offset for the number of fine bits compared to their "fair share" of total/N */
offset = bits[j]-offset*N*C;
if (offset < 0)
offset = 0;
ebits[j] = (2*offset+d)/(2*d);
fine_priority[j] = ebits[j]*d >= offset;
/* Make sure not to bust */
if (C*ebits[j] > (bits[j]>>BITRES))
ebits[j] = bits[j]/C >> BITRES;
if (ebits[j]>7)
ebits[j]=7;
/* The bits used for fine allocation can't be used for pulses */
bits[j] -= C*ebits[j]<<BITRES;
if (bits[j] < 0)
bits[j] = 0;
}
RESTORE_STACK;
}
void compute_allocation(const CELTMode *m, int *offsets, int total, int *pulses, int *ebits, int *fine_priority)
{
int lo, hi, len, j;
VARDECL(int, bits1);
VARDECL(int, bits2);
SAVE_STACK;
len = m->nbEBands;
ALLOC(bits1, len, int);
ALLOC(bits2, len, int);
lo = 0;
hi = m->nbAllocVectors - 1;
while (hi-lo != 1)
{
int psum = 0;
int mid = (lo+hi) >> 1;
for (j=0;j<len;j++)
{
bits1[j] = (m->allocVectors[mid*len+j] + offsets[j])<<BITRES;
if (bits1[j] < 0)
bits1[j] = 0;
psum += bits1[j];
/*printf ("%d ", bits[j]);*/
}
/*printf ("\n");*/
if (psum > (total<<BITRES))
hi = mid;
else
lo = mid;
/*printf ("lo = %d, hi = %d\n", lo, hi);*/
}
/*printf ("interp between %d and %d\n", lo, hi);*/
for (j=0;j<len;j++)
{
bits1[j] = m->allocVectors[lo*len+j] + offsets[j];
bits2[j] = m->allocVectors[hi*len+j] + offsets[j];
if (bits1[j] < 0)
bits1[j] = 0;
if (bits2[j] < 0)
bits2[j] = 0;
}
interp_bits2pulses(m, bits1, bits2, total, pulses, ebits, fine_priority, len);
RESTORE_STACK;
}

144
fmod/lib/libcelt/rate.h Executable file
View file

@ -0,0 +1,144 @@
/* (C) 2007-2008 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RATE_H
#define RATE_H
#define MAX_PULSES 128
#define LOG_MAX_PULSES 7
#define BITRES 4
#define BITROUND 8
#define BITOVERFLOW 30000
#include "cwrs.h"
static FMOD_INLINE int bits2pulses(const CELTMode *m, const celt_int16_t *cache, int N, int bits)
{
int i;
int lo, hi;
lo = 0;
hi = MAX_PULSES-1;
#if 0 /* Disabled until we can make that useful */
/* Use of more than MAX_PULSES is disabled until we are able to cwrs that decently */
if (bits > cache[MAX_PULSES-1] && N<=4)
{
/*int pulses;
pulses = 127;
while (16 + log2_frac(2*(pulses+1)*(pulses+1) + 1, 4) <= bits && pulses < 32767)
pulses++;*/
lo = 127;
switch (N)
{
case 3:
hi = 1024;
for (i=0;i<10;i++)
{
int pulses = (lo+hi)>>1;
if (log2_frac(((UMUL16_16(pulses,pulses)>>1)+1)>>1, 4) > bits)
hi = pulses;
else
lo = pulses;
}
break;
case 4:
hi = 1024;
for (i=0;i<10;i++)
{
int pulses = (lo+hi)>>1;
if (log2_frac((UMUL32(UMUL16_16(pulses,pulses)+2,pulses))/3<<3, 4) > bits)
hi = pulses;
else
lo = pulses;
}
break;
}
return lo;
}
#endif
/* Instead of using the "bisection condition" we use a fixed number of
iterations because it should be faster */
/*while (hi-lo != 1)*/
for (i=0;i<LOG_MAX_PULSES;i++)
{
int mid = (lo+hi)>>1;
/* OPT: Make sure this is implemented with a conditional move */
if (cache[mid] >= bits)
hi = mid;
else
lo = mid;
}
if (bits-cache[lo] <= cache[hi]-bits)
return lo;
else
return hi;
}
static FMOD_INLINE int pulses2bits(const celt_int16_t *cache, int N, int pulses)
{
#if 0 /* Use of more than MAX_PULSES is disabled until we are able to cwrs that decently */
if (pulses > 127)
{
int bits;
switch (N)
{
case 3:
bits = log2_frac(((UMUL16_16(pulses,pulses)>>1)+1)>>1, 4);
break;
case 4:
bits = log2_frac((UMUL32(UMUL16_16(pulses,pulses)+2,pulses))/3<<3, 4);
break;
}
/*printf ("%d <- %d\n", bits, pulses);*/
return bits;
}
#endif
return cache[pulses];
}
/** Computes a cache of the pulses->bits mapping in each band */
celt_int16_t **compute_alloc_cache(CELTMode *m, int C);
/** Compute the pulse allocation, i.e. how many pulses will go in each
* band.
@param m mode
@param offsets Requested increase or decrease in the number of bits for
each band
@param total Number of bands
@param pulses Number of pulses per band (returned)
@return Total number of bits allocated
*/
void compute_allocation(const CELTMode *m, int *offsets, int total, int *pulses, int *ebits, int *fine_priority);
#endif

146
fmod/lib/libcelt/stack_alloc.h Executable file
View file

@ -0,0 +1,146 @@
/* Copyright (C) 2002 Jean-Marc Valin */
/**
@file stack_alloc.h
@brief Temporary memory allocation on stack
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef STACK_ALLOC_H
#define STACK_ALLOC_H
#define USE_ALLOCA // CPS
#ifdef USE_ALLOCA
# ifdef WIN32
# include <malloc.h>
# else
# ifdef HAVE_ALLOCA_H
# include <alloca.h>
# else
# include <stdlib.h>
# endif
# endif
#endif
/**
* @def ALIGN(stack, size)
*
* Aligns the stack to a 'size' boundary
*
* @param stack Stack
* @param size New size boundary
*/
/**
* @def PUSH(stack, size, type)
*
* Allocates 'size' elements of type 'type' on the stack
*
* @param stack Stack
* @param size Number of elements
* @param type Type of element
*/
/**
* @def VARDECL(var)
*
* Declare variable on stack
*
* @param var Variable to declare
*/
/**
* @def ALLOC(var, size, type)
*
* Allocate 'size' elements of 'type' on stack
*
* @param var Name of variable to allocate
* @param size Number of elements
* @param type Type of element
*/
#if defined(VAR_ARRAYS)
#define VARDECL(type, var)
#define ALLOC(var, size, type) type var[size]
#define SAVE_STACK
#define RESTORE_STACK
#define ALLOC_STACK
#elif defined(USE_ALLOCA)
#define VARDECL(type, var) type *var
#define ALLOC(var, size, type) var = ((type*)alloca(sizeof(type)*(size)))
#define SAVE_STACK
#define RESTORE_STACK
#define ALLOC_STACK
#else
#ifdef CELT_C
char *global_stack=0;
#else
extern char *global_stack;
#endif /*CELT_C*/
#ifdef ENABLE_VALGRIND
#include <valgrind/memcheck.h>
#ifdef CELT_C
char *global_stack_top=0;
#else
extern char *global_stack_top;
#endif /*CELT_C*/
#define ALIGN(stack, size) ((stack) += ((size) - (long)(stack)) & ((size) - 1))
#define PUSH(stack, size, type) (VALGRIND_MAKE_MEM_NOACCESS(stack, global_stack_top-stack),ALIGN((stack),sizeof(type)/sizeof(char)),VALGRIND_MAKE_MEM_UNDEFINED(stack, ((size)*sizeof(type)/sizeof(char))),(stack)+=(2*(size)*sizeof(type)/sizeof(char)),(type*)((stack)-(2*(size)*sizeof(type)/sizeof(char))))
#define RESTORE_STACK ((global_stack = _saved_stack),VALGRIND_MAKE_MEM_NOACCESS(global_stack, global_stack_top-global_stack))
#define ALLOC_STACK ((global_stack = (global_stack==0) ? ((global_stack_top=celt_alloc_scratch(GLOBAL_STACK_SIZE*2)+(GLOBAL_STACK_SIZE*2))-(GLOBAL_STACK_SIZE*2)) : global_stack),VALGRIND_MAKE_MEM_NOACCESS(global_stack, global_stack_top-global_stack))
#else
#define ALIGN(stack, size) ((stack) += ((size) - (long)(stack)) & ((size) - 1))
#define PUSH(stack, size, type) (ALIGN((stack),sizeof(type)/sizeof(char)),(stack)+=(size)*(sizeof(type)/sizeof(char)),(type*)((stack)-(size)*(sizeof(type)/sizeof(char))))
#define RESTORE_STACK (global_stack = _saved_stack)
#define ALLOC_STACK (global_stack = (global_stack==0) ? celt_alloc_scratch(GLOBAL_STACK_SIZE) : global_stack)
#endif /*ENABLE_VALGRIND*/
#include "os_support.h"
#define VARDECL(type, var) type *var
#define ALLOC(var, size, type) var = PUSH(global_stack, size, type)
#define SAVE_STACK char *_saved_stack = global_stack;
#endif /*VAR_ARRAYS*/
#endif /*STACK_ALLOC_H*/

393
fmod/lib/libcelt/vq.c Executable file
View file

@ -0,0 +1,393 @@
/* (C) 2007-2008 Jean-Marc Valin, CSIRO
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "mathops.h"
#include "cwrs.h"
#include "vq.h"
#include "arch.h"
#include "os_support.h"
/** Takes the pitch vector and the decoded residual vector, computes the gain
that will give ||p+g*y||=1 and mixes the residual with the pitch. */
static void mix_pitch_and_residual(int * celt_restrict iy, celt_norm_t * celt_restrict X, int N, int K, const celt_norm_t * celt_restrict P)
{
int i;
celt_word32_t Ryp, Ryy, Rpp;
celt_word16_t ryp, ryy, rpp;
celt_word32_t g;
VARDECL(celt_norm_t, y);
#ifdef FIXED_POINT
int yshift;
#endif
SAVE_STACK;
#ifdef FIXED_POINT
yshift = 13-celt_ilog2(K);
#endif
ALLOC(y, N, celt_norm_t);
Rpp = 0;
i=0;
do {
Rpp = MAC16_16(Rpp,P[i],P[i]);
y[i] = SHL16(iy[i],yshift);
} while (++i < N);
Ryp = 0;
Ryy = 0;
/* If this doesn't generate a dual MAC (on supported archs), fire the compiler guy */
i=0;
do {
Ryp = MAC16_16(Ryp, y[i], P[i]);
Ryy = MAC16_16(Ryy, y[i], y[i]);
} while (++i < N);
ryp = ROUND16(Ryp,14);
ryy = ROUND16(Ryy,14);
rpp = ROUND16(Rpp,14);
/* g = (sqrt(Ryp^2 + Ryy - Rpp*Ryy)-Ryp)/Ryy */
g = MULT16_32_Q15(celt_sqrt(MAC16_16(Ryy, ryp,ryp) - MULT16_16(ryy,rpp)) - ryp,
celt_rcp(SHR32(Ryy,9)));
i=0;
do
X[i] = ADD16(P[i], ROUND16(MULT16_16(y[i], g),11));
while (++i < N);
RESTORE_STACK;
}
#ifdef FMOD_CELT_ENCODER
void alg_quant(celt_norm_t *X, celt_mask_t *W, int N, int K, celt_norm_t *P, ec_enc *enc)
{
VARDECL(celt_norm_t, y);
VARDECL(int, iy);
VARDECL(celt_word16_t, signx);
int j, is;
celt_word16_t s;
int pulsesLeft;
celt_word32_t sum;
celt_word32_t xy, yy, yp;
celt_word16_t Rpp;
int N_1; /* Inverse of N, in Q14 format (even for float) */
#ifdef FIXED_POINT
int yshift;
#endif
SAVE_STACK;
#ifdef FIXED_POINT
yshift = 13-celt_ilog2(K);
#endif
ALLOC(y, N, celt_norm_t);
ALLOC(iy, N, int);
ALLOC(signx, N, celt_word16_t);
N_1 = 512/N;
sum = 0;
j=0; do {
X[j] -= P[j];
if (X[j]>0)
signx[j]=1;
else {
signx[j]=-1;
X[j]=-X[j];
P[j]=-P[j];
}
iy[j] = 0;
y[j] = 0;
sum = MAC16_16(sum, P[j],P[j]);
} while (++j<N);
Rpp = ROUND16(sum, NORM_SHIFT);
celt_assert2(Rpp<=NORM_SCALING, "Rpp should never have a norm greater than unity");
xy = yy = yp = 0;
pulsesLeft = K;
/* Do a pre-search by projecting on the pyramid */
if (K > (N>>1))
{
celt_word16_t rcp;
sum=0;
j=0; do {
sum += X[j];
} while (++j<N);
#ifdef FIXED_POINT
if (sum <= K)
#else
if (sum <= EPSILON)
#endif
{
X[0] = QCONST16(1.f,14);
j=1; do
X[j]=0;
while (++j<N);
sum = QCONST16(1.f,14);
}
/* Do we have sufficient accuracy here? */
rcp = EXTRACT16(MULT16_32_Q16(K-1, celt_rcp(sum)));
j=0; do {
#ifdef FIXED_POINT
/* It's really important to round *towards zero* here */
iy[j] = MULT16_16_Q15(X[j],rcp);
#else
iy[j] = floor(rcp*X[j]);
#endif
y[j] = SHL16(iy[j],yshift);
yy = MAC16_16(yy, y[j],y[j]);
xy = MAC16_16(xy, X[j],y[j]);
yp += P[j]*y[j];
y[j] *= 2;
pulsesLeft -= iy[j];
} while (++j<N);
}
celt_assert2(pulsesLeft>=1, "Allocated too many pulses in the quick pass");
while (pulsesLeft > 1)
{
int pulsesAtOnce=1;
int best_id;
celt_word16_t magnitude;
celt_word32_t best_num = -VERY_LARGE16;
celt_word16_t best_den = 0;
#ifdef FIXED_POINT
int rshift;
#endif
/* Decide on how many pulses to find at once */
pulsesAtOnce = (pulsesLeft*N_1)>>9; /* pulsesLeft/N */
if (pulsesAtOnce<1)
pulsesAtOnce = 1;
#ifdef FIXED_POINT
rshift = yshift+1+celt_ilog2(K-pulsesLeft+pulsesAtOnce);
#endif
magnitude = SHL16(pulsesAtOnce, yshift);
best_id = 0;
/* The squared magnitude term gets added anyway, so we might as well
add it outside the loop */
yy = MAC16_16(yy, magnitude,magnitude);
/* Choose between fast and accurate strategy depending on where we are in the search */
/* This should ensure that anything we can process will have a better score */
j=0;
do {
celt_word16_t Rxy, Ryy;
/* Select sign based on X[j] alone */
s = magnitude;
/* Temporary sums of the new pulse(s) */
Rxy = EXTRACT16(SHR32(MAC16_16(xy, s,X[j]),rshift));
/* We're multiplying y[j] by two so we don't have to do it here */
Ryy = EXTRACT16(SHR32(MAC16_16(yy, s,y[j]),rshift));
/* Approximate score: we maximise Rxy/sqrt(Ryy) (we're guaranteed that
Rxy is positive because the sign is pre-computed) */
Rxy = MULT16_16_Q15(Rxy,Rxy);
/* The idea is to check for num/den >= best_num/best_den, but that way
we can do it without any division */
/* OPT: Make sure to use conditional moves here */
if (MULT16_16(best_den, Rxy) > MULT16_16(Ryy, best_num))
{
best_den = Ryy;
best_num = Rxy;
best_id = j;
}
} while (++j<N);
j = best_id;
is = pulsesAtOnce;
s = SHL16(is, yshift);
/* Updating the sums of the new pulse(s) */
xy = xy + MULT16_16(s,X[j]);
/* We're multiplying y[j] by two so we don't have to do it here */
yy = yy + MULT16_16(s,y[j]);
yp = yp + MULT16_16(s, P[j]);
/* Only now that we've made the final choice, update y/iy */
/* Multiplying y[j] by 2 so we don't have to do it everywhere else */
y[j] += 2*s;
iy[j] += is;
pulsesLeft -= pulsesAtOnce;
}
if (pulsesLeft > 0)
{
celt_word16_t g;
celt_word16_t best_num = -VERY_LARGE16;
celt_word16_t best_den = 0;
int best_id = 0;
celt_word16_t magnitude = SHL16(1, yshift);
/* The squared magnitude term gets added anyway, so we might as well
add it outside the loop */
yy = MAC16_16(yy, magnitude,magnitude);
j=0;
do {
celt_word16_t Rxy, Ryy, Ryp;
celt_word16_t num;
/* Select sign based on X[j] alone */
s = magnitude;
/* Temporary sums of the new pulse(s) */
Rxy = ROUND16(MAC16_16(xy, s,X[j]), 14);
/* We're multiplying y[j] by two so we don't have to do it here */
Ryy = ROUND16(MAC16_16(yy, s,y[j]), 14);
Ryp = ROUND16(MAC16_16(yp, s,P[j]), 14);
/* Compute the gain such that ||p + g*y|| = 1
...but instead, we compute g*Ryy to avoid dividing */
g = celt_psqrt(MULT16_16(Ryp,Ryp) + MULT16_16(Ryy,QCONST16(1.f,14)-Rpp)) - Ryp;
/* Knowing that gain, what's the error: (x-g*y)^2
(result is negated and we discard x^2 because it's constant) */
/* score = 2*g*Rxy - g*g*Ryy;*/
#ifdef FIXED_POINT
/* No need to multiply Rxy by 2 because we did it earlier */
num = MULT16_16_Q15(ADD16(SUB16(Rxy,g),Rxy),g);
#else
num = g*(2*Rxy-g);
#endif
if (MULT16_16(best_den, num) > MULT16_16(Ryy, best_num))
{
best_den = Ryy;
best_num = num;
best_id = j;
}
} while (++j<N);
iy[best_id] += 1;
}
j=0;
do {
P[j] = MULT16_16(signx[j],P[j]);
X[j] = MULT16_16(signx[j],X[j]);
if (signx[j] < 0)
iy[j] = -iy[j];
} while (++j<N);
encode_pulses(iy, N, K, enc);
/* Recompute the gain in one pass to reduce the encoder-decoder mismatch
due to the recursive computation used in quantisation. */
mix_pitch_and_residual(iy, X, N, K, P);
RESTORE_STACK;
}
#endif
/** Decode pulse vector and combine the result with the pitch vector to produce
the final normalised signal in the current band. */
void alg_unquant(celt_norm_t *X, int N, int K, celt_norm_t *P, ec_dec *dec)
{
VARDECL(int, iy);
SAVE_STACK;
ALLOC(iy, N, int);
decode_pulses(iy, N, K, dec);
mix_pitch_and_residual(iy, X, N, K, P);
RESTORE_STACK;
}
celt_word16_t renormalise_vector(celt_norm_t *X, celt_word16_t value, int N, int stride)
{
int i;
celt_word32_t E = EPSILON;
celt_word16_t rE;
celt_word16_t g;
celt_norm_t *xptr = X;
for (i=0;i<N;i++)
{
E = MAC16_16(E, *xptr, *xptr);
xptr += stride;
}
rE = celt_sqrt(E);
#ifdef FIXED_POINT
if (rE <= 128)
g = Q15ONE;
else
#endif
g = MULT16_16_Q15(value,celt_rcp(SHL32(rE,9)));
xptr = X;
for (i=0;i<N;i++)
{
*xptr = PSHR32(MULT16_16(g, *xptr),8);
xptr += stride;
}
return rE;
}
static void fold(const CELTMode *m, int N, celt_norm_t *Y, celt_norm_t * celt_restrict P, int N0, int B)
{
int j;
const int C = CHANNELS(m);
int id = (N0*C) % (C*B);
/* Here, we assume that id will never be greater than N0, i.e. that
no band is wider than N0. In the unlikely case it happens, we set
everything to zero */
/*{
int offset = (N0*C - (id+C*N))/2;
if (offset > C*N0/16)
offset = C*N0/16;
offset -= offset % (C*B);
if (offset < 0)
offset = 0;
//printf ("%d\n", offset);
id += offset;
}*/
if (id+C*N>N0*C)
for (j=0;j<C*N;j++)
P[j] = 0;
else
for (j=0;j<C*N;j++)
P[j] = Y[id++];
}
void intra_fold(const CELTMode *m, celt_norm_t * celt_restrict x, int N, int *pulses, celt_norm_t *Y, celt_norm_t * celt_restrict P, int N0, int B)
{
int c;
celt_word16_t pred_gain;
const int C = CHANNELS(m);
fold(m, N, Y, P, N0, B);
c=0;
do {
int K = pulses[c];
if (K==0)
pred_gain = Q15ONE;
else
pred_gain = celt_div((celt_word32_t)MULT16_16(Q15_ONE,N),(celt_word32_t)(N+2*K*(K+1)));
renormalise_vector(P+c, pred_gain, N, C);
} while (++c < C);
}

79
fmod/lib/libcelt/vq.h Executable file
View file

@ -0,0 +1,79 @@
/* (C) 2007-2008 Jean-Marc Valin, CSIRO
*/
/**
@file vq.h
@brief Vector quantisation of the residual
*/
/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef VQ_H
#define VQ_H
#include "entenc.h"
#include "entdec.h"
#include "modes.h"
/** Algebraic pulse-vector quantiser. The signal x is replaced by the sum of
* the pitch and a combination of pulses such that its norm is still equal
* to 1. This is the function that will typically require the most CPU.
* @param x Residual signal to quantise/encode (returns quantised version)
* @param W Perceptual weight to use when optimising (currently unused)
* @param N Number of samples to encode
* @param K Number of pulses to use
* @param p Pitch vector (it is assumed that p+x is a unit vector)
* @param enc Entropy encoder state
*/
void alg_quant(celt_norm_t *X, celt_mask_t *W, int N, int K, celt_norm_t *P, ec_enc *enc);
/** Algebraic pulse decoder
* @param x Decoded normalised spectrum (returned)
* @param N Number of samples to decode
* @param K Number of pulses to use
* @param p Pitch vector (automatically added to x)
* @param dec Entropy decoder state
*/
void alg_unquant(celt_norm_t *X, int N, int K, celt_norm_t *P, ec_dec *dec);
celt_word16_t renormalise_vector(celt_norm_t *X, celt_word16_t value, int N, int stride);
/** Intra-frame predictor that matches a section of the current frame (at lower
* frequencies) to encode the current band.
* @param x Residual signal to quantise/encode (returns quantised version)
* @param W Perceptual weight
* @param N Number of samples to encode
* @param K Number of pulses to use
* @param Y Lower frequency spectrum to use, normalised to the same standard deviation
* @param P Pitch vector (it is assumed that p+x is a unit vector)
* @param B Stride (number of channels multiplied by the number of MDCTs per frame)
* @param N0 Number of valid offsets
*/
void intra_fold(const CELTMode *m, celt_norm_t * celt_restrict x, int N, int *pulses, celt_norm_t *Y, celt_norm_t * celt_restrict P, int N0, int B);
#endif /* VQ_H */